How to avoid inserting duplicate records when using a T-SQL Merge statement

后端 未结 3 711
再見小時候
再見小時候 2021-02-19 00:32

I am attempting to insert many records using T-SQL\'s MERGE statement, but my query fails to INSERT when there are duplicate records in the source table. The failure is caused b

3条回答
  •  被撕碎了的回忆
    2021-02-19 01:01

    Solved to your new specification. Only inserting the highest value of col4: This time I used a group by to prevent duplicate rows.

    MERGE INTO dbo.tbl1 AS tbl 
    USING (SELECT col2,col3, max(col4) col4 FROM #tmp group by col2,col3) AS src 
    ON (tbl.col2 = src.col2 AND tbl.col3 = src.col3) 
    WHEN NOT MATCHED THEN  
        INSERT (col2,col3,col4) 
        VALUES (src.col2,src.col3,src.col4); 
    

提交回复
热议问题