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 [email protected] 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.
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)
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With