Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid Duplicate values for INSERT in SQL?

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?

like image 714
barsan Avatar asked Jul 03 '13 08:07

barsan


People also ask

How do I stop duplicate SQL results?

SQL Delete Duplicate Rows using Group By and Having Clause According to Delete Duplicate Rows in SQL, for finding duplicate rows, you need to use the SQL GROUP BY clause. The COUNT function can be used to verify the occurrence of a row using the Group by clause, which groups data according to the given columns.

How do I insert distinct records in SQL?

INSERT DISTINCT Records INTO New Tables After "INSERT INTO", you specify the target table's name - organizations in the below case. Then you select the columns that should be copied over from the source table – unviversity_professors in this case. You use the "DISTINCT" keyword to only copy over distinct organizations.


1 Answers

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]);
like image 172
gbn Avatar answered Oct 16 '22 07:10

gbn