Skip to content
Advertisement

How can I prevent inserting duplicate data into a SQL Server table?

I have a series of data that need to be written into SQL, what should I do to check the data in SQL to prevent same data inserted into table?

Example data to be inserted:

If the 4th data is John again, I want the system to skip the duplicate record (John).

So far I have:

i got the string value checkname that is last inserted, what should i do check the data?

Advertisement

Answer

First, you can prevent a duplicate from ever occurring in the table by using a unique index or constraint. An index/constraint can work in concert with the suggestions below. If you only use a unique index and not one of the below solutions, inserting a duplicate record will throw an error and you will need to handle that on the other end.

Additionally, I would probably insert the data via a stored procedure that checks to see if the row already exists. To do that, you can use either a MERGE statement, as shown in this pseudo code:

or, you could check for the records existence and insert or update manually:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement