开发者

SQL Insertion without duplication

开发者 https://www.devze.com 2023-01-19 20:24 出处:网络
Is there a specific command 开发者_运维问答for SQL Server in order to INSERT a lot of rows with the condition : if a row already exists in database doesn\'t duplicate it during insertion ?

Is there a specific command 开发者_运维问答for SQL Server in order to INSERT a lot of rows with the condition : if a row already exists in database doesn't duplicate it during insertion ?

Edited

In a sqlbulkcopy, I'd like to avoid exception because a row is already in the table ?


You can use the MERGE command for this. Example Usage.

CREATE TABLE #A(
 [id] [int] NOT NULL PRIMARY KEY CLUSTERED,
 [C] [varchar](200) NOT NULL)


    MERGE #A AS target
    USING (SELECT 3, 'C') AS source (id, C)
    ON (target.id = source.id)
    /*Uncomment for Upsert Semantics
       WHEN MATCHED THEN 
        UPDATE SET C = source.C */
    WHEN NOT MATCHED THEN    
        INSERT (id, C)
        VALUES (source.id, source.C);

Edit Though you say in your edit this is for a bulk copy? You could also investigate the "Ignore Duplicate Keys" option on your index.


How to do it in T-SQL is discussed here (article is a bit old though)

0

精彩评论

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

关注公众号