MSSQL stored proc Duplicate Key Error handling

Posted on 2008-10-01
Last Modified: 2013-11-15
Is it possible to know witch row is duplicated during a insert into
Here's my example:

-- MSSQL Stored Proc
Begin Try
   Insert into A (Select * From B)
End Try
Begin Catch
 -- Here i want to know witch row was not inserted because of a duplicated error
End Catch

Many thanks

Question by:pascalbergeron
  • 2
  • 2
LVL 11

Accepted Solution

aaronakin earned 250 total points
ID: 22615251
Not really, but you do this...

    FROM B
    WHERE PKColumnName NOT IN (SELECT PKColumnName FROM A)
LVL 39

Expert Comment

ID: 22615273
error_number() = 2627
Begin Try
   Insert into A (Select * From B)
End Try
Begin Catch
  if error_number() = 2627
    print 'Violation of %ls constraint '--'%.*ls'. Cannot insert duplicate key in object '%.*ls'.'
End Catch

Open in new window

LVL 39

Assisted Solution

BrandonGalderisi earned 250 total points
ID: 22615303
That's detecting it... to prevent it.

insert into A
select b.* from b
 left outer join a
  on b.WhatFieldLinks = a.WhatFieldLinks
where a.WhatFieldLinks is null
LVL 11

Expert Comment

ID: 22615379
BrandonGalderisi, I believe your first solution will catch the violation error, but it will not continue to insert the non-duplicate records.

pascalbergeron, you're best choice would be to use either query that BrandonGalderisi or I provided to make sure the duplicate rows do not get inserted.

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Run SQL Server Proc from Access 11 31
T-SQL: Do I need CLUSTERED here? 13 45
Flattening heirachies 3 31
performance query 4 24
Read about achieving the basic levels of HRIS security in the workplace.
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question