开发者

How do I add a record only if it doesn't already exist in 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 th开发者_开发知识库anks,


IF NOT EXISTS (SELECT * FROM Process WHERE process_name = 'xxx')
INSERT INTO Process (process_name, Full_Name, Version) 
VALUES ('xxx', 'yyy', 'zzz')


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜