Solved

Error handling in Insert

Posted on 2013-01-31
3
163 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 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

Edgartown IT Case Study

Learn about Edgartown's quest to ensure the safety and security of the entire town's employee and citizen data. Read the case study!

Question has a verified solution.

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

Audit has been really one of the more interesting, most useful, yet difficult to maintain topics in the history of SQL Server. In earlier versions of SQL people had very few options for auditing in SQL Server. It typically meant using SQL Trace …
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…
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

726 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