How to avoid Duplicate values for INSERT in SQL?

前端 未结 6 646

I have one table named:

Delegates

This table has four fields:

ID(Auto increment, Primary)
MemberNo, FromYr, ToYr
         


        
6条回答
  •  悲哀的现实
    2020-11-27 08:19

    You can avoid inserting duplicates with this simple, one line of code:

    INSERT INTO Delegates (MemNo, FromYr, ToYr) SELECT @MemNo, @FromYr, @ToYr WHERE NOT EXISTS (SELECT 1 FROM Delegates d WHERE d.MemNo=@MemNo AND d.FromYr=@FromYr)

    If it's a high load environment where another command could insert the duplicate while this command is executing, you can use the WITH(HOLDLOCK) hint.

提交回复
热议问题