[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Error handling in Insert

Posted on 2013-01-31
3
Medium Priority
?
169 Views
Last Modified: 2013-01-31
Hello Experts!!

I am trying to load a table using Insert statement.

My script will insert fine for the first time and when I run the same script once again, I ll get an error saying cannot insert duplicate values ( I have two columns and both are primary keys, so I cant insert duplicate values )

Is there a way to re-write it so that when I insert the second time and if there are any new records, it will insert them and the rest wont be inserted.

CAN WE DO THIS WITHOUT USING UPSERT/MERGE ??

Thanks!!!
0
Comment
Question by:ravichand-sql
3 Comments
 
LVL 12

Accepted Solution

by:
Jared_S earned 2000 total points
ID: 38840404
Why not just eliminate the records prior to insert by using a NOT EXISTS statement against your table?

INSERT INTO Table1

SELECT * FROM Table2
WHERE NOT EXISTS
(SELECT null FROM Table1 WHERE Table1.Key = Table2.Key)
0
 
LVL 40

Expert Comment

by:lcohan
ID: 38840693
Same idea but using an EXCEPT sql function:

INSERT INTO Table1
SELECT * FROM Table2
EXCEPT
SELECT * FROM Table1 WHERE Table1.RowKey = Table2.RowKey
0
 

Author Comment

by:ravichand-sql
ID: 38840853
Thanks, it helped!!
0

Featured Post

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

Question has a verified solution.

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

Naughty Me. While I was changing the database name from DB1 to DB_PROD1 (yep it's not real database name ^v^), I changed the database name and notified my application fellows that I did it. They turn on the application, and everything is working. A …
How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
Integration Management Part 2
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …

867 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