Solved

Error handling in Insert

Posted on 2013-01-31
3
158 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 500 total points
Comment Utility
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 39

Expert Comment

by:lcohan
Comment Utility
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
Comment Utility
Thanks, it helped!!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

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 …
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

728 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

9 Experts available now in Live!

Get 1:1 Help Now