Gopal
Gopal

Reputation: 11982

IF Not Exist then Inseting a value in the table

Using SQL Server 2005, vb.net

Table1

Name FromDate ToDate

Raja 12/02/2010 14/02/2010
Ravi 14/02/2010 15/02/2010
Ramu 18/02/2010 21/02/2010
...,

Insert into Table1 values('" & textbox1.text & "', '" & textbox2.text & "'. '" & textbox3.text & "'", con)

When i try to insert a value into table1 it will compare the table values if it is same, It Should throw a error msg "Name and Date Already Exist" otherwise Insert a value.

Before Inserting i want to check a textbox value with table value.

Can any one give a sample idea or code for this.

Upvotes: 0

Views: 1802

Answers (2)

marc_s
marc_s

Reputation: 754938

In T-SQL:

IF EXISTS(SELECT * FROM dbo.Table1 WHERE Name = @Name AND FromDate = @FromDate AND ToDate = @ToDate)
   RAISERROR (N'Values already exist', 10, 1)
ELSE
   INSERT INTO dbo.Table1(Name, FromDate, ToDate)
   VALUES(@Name, @FromDate, @ToDate)

And then call this from a parametrized query in your VB.NET code.

For details about RAISERROR, see the MSDN docs: http://msdn.microsoft.com/en-us/library/ms178592.aspx. The value "10" here is the severity, the "1" is the state. You can see a list of all available severities and states in the MSDN docs.

Or wrap the whole statement into a stored proc that deals with all of this, and just call that stored proc.


UPDATE:

Create a stored proc:

CREATE PROCEDURE dbo.InsertData(@Name VARCHAR(50), @FromDate DATETIME, @ToDate DAETIME)
AS BEGIN
   BEGIN TRANSACTION

   IF EXISTS(SELECT * FROM dbo.Table1 WHERE Name = @Name AND FromDate = @FromDate AND ToDate = @ToDate)
      ROLLBACK TRANSACTION
      RAISERROR (N'Values already exist', 10, 1)
   ELSE
      INSERT INTO dbo.Table1(Name, FromDate, ToDate)
      VALUES(@Name, @FromDate, @ToDate)

      COMMIT TRANSACTION
END

and then call that from your code (I'm not fluent in VB.NET - this is C#, but should be simple enough to translate):

using(SqlConnection _con = new SqlConnection('your connection string here'))
{
    using(SqlCommand _cmd = new SqlCommand("InsertData", _con)
    {
        _cmd.CommandType = CommandType.StoredProcedure;

        // add parameters as necessary
        _cmd.Parameters.AddWithValue("@Name", "Your Name");
        _cmd.Parameters.AddWithValue("@FromDate", "20100101");
        _cmd.Parameters.AddWithValue("@ToDate", "20100331");

        try
        {
            // open connection, execute stored proc, close connection
            _con.Open();
            _cmd.ExecuteNonQuery();
            _con.Close();
        } 
        catch(SqlException sqlexc)
        {
            // handle SQL exception
        }
    }
}

That nicely encapsulates everything into a single method - does that work for you??

Upvotes: 3

Aristos
Aristos

Reputation: 66641

Use the "IF NOT EXIST" command

IF NOT EXISTS (SELECT * FROM Table WHERE YourContition) INSERT INTO Table (a,b) VALUES (@c1,@c2)

Upvotes: 2

Related Questions