views:

104

answers:

2

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.

+3  A: 

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??

marc_s
What you mean by 10
Gopal
@Marc_S, I cannot able to make if cmd =new Sqlcommand("Your Query", con). In vb.net if sqlcommand is not accepting. Do you have any idea regarding this.
Gopal
what if another process inserts the same row between your IF EXISTS (SELECT... and your INSERT??? Don't you need to add a transaction and a (UPDLOCK, HOLDLOCK) hint on the `SELECT`
KM
@KM: yes, ultimately, that would be the best solution - wrap everything in a transaction. I was just trying to get the OP started on even inserting any data at all..... but you're absolutely right
marc_s
@Marc_s - When i try to insert a same record, your code was not allowing to insert but when i close the form, then again load the form, your code is allowing to insert a same record.
Gopal
@Gopal: there must be some other problem here - this check on the database will work - no matter whether or not you "close your form". Either your data wasn't written to the database, or you're doing something else to get around this....
marc_s
@Marc_S - I think there is a problem in store procedure, why because when i click add button, then store procedure is running, next time i try to add the same value, query is not allowing to add, because store is procedure is already running. Then i closed the form, Store procedure also closing, when i load the form. I adding a same value, query is allowing to add the same value, because there is no value in a @name, @FromDate, @Todate. Did you get my point what i am saying. Only this is a problem or what else?
Gopal
@GOpal: updated the stored proc to include transaction handling - does it work now??
marc_s
+1  A: 

Use the "IF NOT EXIST" command

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