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

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.

910 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

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now