troubleshooting Question

MS SQL Update an Existing Row and Insert the New Row

Avatar of j_heck
j_heck asked on
Microsoft SQL ServerMicrosoft DevelopmentMicrosoft SQL Server 2008
5 Comments1 Solution866 ViewsLast Modified:
I have two tables, TableA & TableB, TableA is the production table and TableB is a working table.  I need to Insert the rows in TableB that do not exist in TableA and update the rows in TableA that are in TableB, which I can do using the MERGE command.  The problem I am running into is trying to Insert the row in TableB as a new row if it already exist in TableA.  The MERGE command does not allow the insertion of a row on the WHEN MATCHED in the MERGE command.  By updating the MATCHED row in TableA first before inserting the new row in TableB will keep the data unique.

I know I can do this by reading the table multiple times, once to do the UPDATE and then again to do the INSERT command.  I would like to skip the double read by using the MERGE command if possible.  If it cant be done then I will just run two pieces of code; one for UPDATE and one for INSERT

Any suggestions?

Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 5 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 5 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros