views:

95

answers:

3

Hi,
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,

+6  A: 
IF NOT EXISTS (SELECT * FROM Process WHERE process_name = 'xxx')
INSERT INTO Process (process_name, Full_Name, Version) 
VALUES ('xxx', 'yyy', 'zzz')
RedFilter
Thanks, great answer
menacheb
A: 

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
AdaTheDev
+3  A: 

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.

Daniel Renshaw
+1 Beat me to it.
ParmesanCodice