SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 insert help
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

oracle765
Starting Member

Australia
13 Posts

Posted - 03/06/2013 :  19:17:52  Show Profile  Reply with Quote
I am trying to insert records into the database as follows
insert into lookuptable
select * from lookuptable1

which produces
Msg 2627, Level 14, State 1, Line 1
Violation of UNIQUE KEY constraint 'uqLookuptable1cols1'. Cannot insert duplicate key in object 'dbo.lookuptable'.
The statement has been terminated.

Is there a way to handle this error so I can carry on inserting the rest of the records into the table

A Lynch

James K
Flowing Fount of Yak Knowledge

3565 Posts

Posted - 03/06/2013 :  19:50:19  Show Profile  Reply with Quote
See script below - replace the "uniqueColumn" with the column that is referenced in the constraint.
insert into lookuptable
select * from lookuptable1 a
WHERE NOT EXISTS (SELECT * FROM lookuptable b
                  WHERE b.uniqueColumn = a.uniqueColumn)
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000