Reputation: 485
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,
Upvotes: 4
Views: 4604
Reputation: 171411
IF NOT EXISTS (SELECT * FROM Process WHERE process_name = 'xxx')
INSERT INTO Process (process_name, Full_Name, Version)
VALUES ('xxx', 'yyy', 'zzz')
Upvotes: 12
Reputation: 34177
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.
Upvotes: 3
Reputation: 147224
Assuming process_name is the PK that you want to check on:
IF NOT EXISTS(SELECT 1 FROM Process WHERE process_name = @ProcessName)
BEGIN
-- Process does not already exist, so INSERT
END
Upvotes: 1