I have 2 simple tables
+------|---------|----------+
+ ID | Value | Test +
+------|---------|----------+
+ 3 | Test | 12345 +
+ 4 | MyVal | 56789 +
+ 5 | Another| 101010 +
+------|---------|----------+
+------|---------|----------+
+ ID | Value | Test +
+------|---------|----------+
+ 3 | Test | 12345 +
+ 7 | MyVal12| 56789 +
+ 5 | Another| 101010 +
+------|---------|----------+
The ID from both tables are primary keys.
In my stored procedure, I create a temporary table like this:
CREATE TABLE #tempTable(
ID int NOT NULL PRIMARY KEY NONCLUSTERED,
FIELD VARCHAR(255))
and the part of my procedure stored with try-catch block:
BEGIN TRY
INSERT INTO #tempTable(ID, FIELD)
EXEC sp_executesql @myCustomSql, @paramList, @param1, @param2 ...
END TRY
BEGIN CATCH
// what to put here ?
END CATCH
I want to add rows to my temporary table (you’ll see the duplicates for ID = 3 and 5) and I want to continue adding. Finally I want to have the following content for table:
+------|---------+
+ ID | FIELD +
+------|---------+
+ 3 | Test +
+ 4 | MyVal +
+ 5 | Another+
+ 7 | MyVal12+
+------|---------+
I gave here a simplified example, in my database I have over one hundred thousand rows and many columns.
Thanks
To ignore (with a warning) attempts to insert duplicate keys rather than raising an error and having the whole statement fail you can use the
IGNORE_DUP_KEYoption.