Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper insert, check for existence of record

Tags:

c#

dapper

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.

like image 452
CSharpNewBee Avatar asked Mar 31 '14 11:03

CSharpNewBee


2 Answers

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)
like image 102
James Avatar answered Sep 20 '22 13:09

James


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!

like image 28
Matt Avatar answered Sep 20 '22 13:09

Matt