How to avoid Duplicate values for INSERT in SQL?

57,219

Solution 1

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)

Solution 2

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]);

Solution 3

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

Solution 4

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
)

Solution 5

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

Share:
57,219
barsan
Author by

barsan

Updated on February 22, 2020

Comments

  • barsan
    barsan over 2 years

    I have one table named:

    Delegates
    

    This table has four fields:

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

    I am inserting with this query:

    INSERT INTO Delegates ([MemNo],[FromYr],[ToYr]) values(@MemNo, @FromYr,@ToYr)
    

    The values comes from user input. One member can be a Delegate for any year that's why I allow them to input as they want. But now problem is they can insert mistakenly one member for the same year more than 2 times. Please help me what can I do now here?