Solved

Error handling in Insert

Posted on 2013-01-31
3
159 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
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 39

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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
tempdb log contention 16 38
sql Total query 2 25
SQL Server 2012 r2 - Sum totals 2 21
convert null in sql server 12 31
There have been several questions about Large Transaction Log Files in SQL Server 2008, and how to get rid of them when disk space has become critical. This article will explain how to disable full recovery and implement simple recovery that carries…
In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

813 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

12 Experts available now in Live!

Get 1:1 Help Now