Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

query to insert or update

Posted on 2015-02-02
3
Medium Priority
?
88 Views
1 Endorsement
Last Modified: 2015-02-13
I'd like to write a script to insert records from one table to a target table if record doesn't exist or update record in target table if exists.  thanks for your help.
1
Comment
Question by:shwelopo
3 Comments
 
LVL 4

Expert Comment

by:Monika Bharti
ID: 40585573
Hi,

This way you can update existing rows, insert rows that exist only in the source, delete rows that appear only in the target.

In your case, you could do something like:
MERGE tableTo AS T
USING tableFrom AS S
      ON (T.product= S._product)
WHEN NOT MATCHED BY TARGET
     THEN INSERT(product, something) VALUES(S._product, S.something)
WHEN MATCHED 
     THEN UPDATE SET T.Something= S.Something
OUTPUT $action, Inserted.*, Deleted.*;

Open in new window


This statement will insert or update rows as needed and return the values that were inserted or overwritten with the OUTPUT clause.
0
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 2000 total points
ID: 40585594
SQL Server and Oracle both have a MERGE statement which are doing what you are asking:
https://msdn.microsoft.com/en-us/library/bb510625.aspx
http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

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

One of the most important things in an application is the query performance. This article intends to give you good tips to improve the performance of your queries.
This month, Experts Exchange sat down with resident SQL expert, Jim Horn, for an in-depth look into the makings of a successful career in SQL.
This video shows how to recover a database from a user managed backup
Via a live example, show how to restore a database from backup after a simulated disk failure using RMAN.

971 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