barsan barsan - 1 year ago 76
SQL Question

How to avoid Duplicate values for INSERT in SQL?

I have one table named:


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?

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download