0

I have a SQL script with about 250 entries that are being inserted. The script on its own runs fine however, I run into problems in case of duplicate entries. I could try doing something like this:

IF NOT EXISTS (SELECT * FROM [TS].[Configs] WHERE [Id] = 15)
INSERT . . . 

However, I cannot write this repeated statement over and over for the 250 entries. I have tried setting Identity_Insert to ON but I still get this error:

Exception Message: Violation of PRIMARY KEY constraint 'Tbl_LangFiles'. Cannot insert duplicate key in object '[TS].[Configs]'

How can I go about only inserting unique entries in this table?

  • try using the MERGE statement for MS Sql Server – Ramkumar Sambandam Apr 27 '22 at 17:57
  • Could you please help me out a bit more? How would that look here? – ScripterPS1230083 Apr 27 '22 at 19:25
  • While asking a question, you need to provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example): (1) DDL and sample data population, i.e. CREATE table(s) plus INSERT T-SQL statements. (2) What you need to do, i.e. logic and your code attempt implementation of it in T-SQL. (3) Desired output, based on the sample data in the #1 above. (4) Your SQL Server version (SELECT @@version;). – Yitzhak Khabinsky Apr 27 '22 at 23:57
  • Read this blog https://www.sqlshack.com/understanding-the-sql-merge-statement/ for Understanding the MS SQLserver MERGE statement refer the link for details https://pastebin.com/1LCrqx2N – Ramkumar Sambandam Apr 28 '22 at 18:11

1 Answers1

-2

Have you tried the UPSERT statement?

UPSERT INTO employees (id, name, email) 
VALUES (2, ‘Dennis’, ‘dennisp@weyland.corp’);

This will attempt to insert a new record on the database, but if it already exists, it will take the parameters and update.

L.

Languré
  • 14
  • 3