1

I am inserting data into a table from temp table as below:

INSERT INTO TBL_PERSON (PropertyID, PERSONID, FULLNAME)          
SELECT DISTINCT PropertyID, PERSONID, FULLNAME FROM #SalesContacts 

The unique key constraint is defined in Tbl_Person using combination of PropertyId, PersonId and FullName columns.

When this query is executed, how can I find out which combination of values are causing unique key constraint exceptions?

I want to log these values with the exception message.

3
  • You could try the INTERSECT clause SELECT DISTINCT PropertyID, PERSONID, FULLNAME FROM #SalesContacts INTERSECT SELECT PropertyID, PERSONID, FULLNAME FROM TBL_PERSON see this link for details on the INTERSECT clause msdn.microsoft.com/en-us/library/ms188055.aspx Aug 3, 2016 at 10:56
  • That's good. But I want to get the values directly in catch block of try-catch. Aug 3, 2016 at 11:00
  • Hmm, i think that might be problematic - Sql Server would stop at the 'first' duplicate and pass control to the CATCH block. what if there are multiple duplicates - it would seem you would want to check for ALL duplicates before trying the insert Aug 3, 2016 at 11:04

1 Answer 1

1

is there a reason this logic won't work for you?

--Find all duplicates and save to temp table
select * into #Duplicates from
(
    SELECT DISTINCT PropertyID, PERSONID, FULLNAME FROM #SalesContacts 
    INTERSECT
    SELECT  PropertyID, PERSONID, FULLNAME FROM TBL_PERSON
) a

--Log the duplicates
insert into ErrorLoggingTable(PropertyID, PERSONID, FULLNAME, ErrorMessage)
select PropertyID, PERSONID, FULLNAME, 'Duplicate Found' from #Duplicates

--Remove the duplicates from the #SalesContacts table
delete a from #SalesContacts a join
#Duplicates b on b.PropertyID and b.PersonID and b.FullName

--Insert the rest
insert into TBL_PERSON (PropertyID, PERSONID, FULLNAME)
    select PropertyID, PERSONID, FULLNAME
1
  • That is fine. I think we can not catch the exception causing values direct in catch block if try-catch. Aug 3, 2016 at 11:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.