Question

So i have been using this method to insert records into my database:

TransactionBlock.Connection.Execute(
                            "INSERT Table(Item,Id)VALUES(@Item, @Id);
                            new {Item,Id = id }, TransactionBlock.Transaction);

I now need to modify this, to first check if the Item/id are already in the database, using the following:

const sql = "IF EXISTS (SELECT * FROM Table, where Item=@Item...etc etc

but I've not come across any examples of how to achieve this. I can achieve this by creating a Stored Procedure, but i'd like to try and accomplish using this approach.

Was it helpful?

Solution

Assuming you are using SQL Server and that you only want to insert the record if it doesn't already exist the SQL you are looking for is

IF NOT EXISTS (SELECT * FROM Table WHERE Id = @Id) 
    INSERT INTO Table(Item, Id) VALUES(@Item, @Id)

OTHER TIPS

INSERT INTO TableName (Item, ID)
SELECT @Item, @Id WHERE NOT EXISTS ( SELECT 1 FROM TableName WHERE Id=@Id )

That will work with one single statement.

Worth noting that depending on the underlying DBMS, you may still have contention - if no lock is issued and many inserts are happening simultaneously you can end up in a condition where the record doesn't exist when it executes the select, but does before it attempts the insert.

If you're dealing with a situation where inserts are happening rapidly, I'd recommend familiarizing yourself with the following:

http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx

Good luck!

Rather than checking if it exists before insertion why not use a try/catch clock to perform the insertion and catch the DuplicateKeyException (not sure if it exists) to determine duplicate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top