Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a record only if it doesn't already exist in SQL Server?

Tags:

c#

sql-server

I have a project in C# with a Sql-server Database.
In that database I have a table named 'Process' and columns named 'process_name', 'Full_Name' and 'Version' (all of the type:nvarchar(50)).
I want to write a query wich will add the new process, only if it doesn't exist in the table yet.
How can I do that?
Many thanks,

like image 232
menacheb Avatar asked Dec 06 '22 02:12

menacheb


2 Answers

IF NOT EXISTS (SELECT * FROM Process WHERE process_name = 'xxx')
INSERT INTO Process (process_name, Full_Name, Version) 
VALUES ('xxx', 'yyy', 'zzz')
like image 197
D'Arcy Rittich Avatar answered Jan 21 '23 05:01

D'Arcy Rittich


You might be interested in the MERGE command which is new to SQL Server 2008.

http://technet.microsoft.com/en-us/library/bb510625.aspx

This allows you to insert rows that don't exist or update records that do exist all in one statement.

like image 37
Daniel Renshaw Avatar answered Jan 21 '23 07:01

Daniel Renshaw