How to avoid Duplicate values for INSERT in SQL?

前端 未结 6 612

I have one table named:

Delegates

This table has four fields:

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


        
相关标签:
6条回答
  • 2020-11-27 08:05

    Try this, (I have not verified)

    INSERT INTO Delegates ([MemNo],[FromYr],[ToYr]) values(@MemNo, @FromYr,@ToYr)
    where @MemNo not in 
    (
        SELECT MemNo FROM words WHERE FromYr = @FromYr
    )
    
    0 讨论(0)
  • 2020-11-27 08:16

    Just add a unique index on that column, then inserting duplicates will cause an error. You can then error handle it if it needs to fail gracefully

    0 讨论(0)
  • 2020-11-27 08:17

    Before inserting check if there is a record with the same values:

    if not exists (select * from Delegates d where d.FromYr = @FromYr and d.MemNo = @MemNo)
        INSERT INTO Delegates ([MemNo],[FromYr],[ToYr]) values(@MemNo, @FromYr,@ToYr)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 08:25

    Use MERGE

    MERGE INTO Delegates D
    USING (values(@MemNo, @FromYr,@ToYr)) X ([MemNo],[FromYr],[ToYr])
    ON (insert unique key join)
    WHEN NOT MATCHED BY TARGET THEN
    INSERT ([MemNo],[FromYr],[ToYr]))
    VALUES (X.[MemNo],X.[FromYr],X.[ToYr]);
    
    0 讨论(0)
  • 2020-11-27 08:27

    make a stored procedure that will first make a check on the whether the values are already contained in the DB. if they arent you will do your insert. If they simply ignore it

    0 讨论(0)
提交回复
热议问题