Solved

query to insert or update

Posted on 2015-02-02
3
73 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
Comment Utility
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 142

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 500 total points
Comment Utility
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

Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

Join & Write a Comment

Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Via a live example, show how to take different types of Oracle backups using RMAN.
Via a live example, show how to shrink a transaction log file down to a reasonable size.

763 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

8 Experts available now in Live!

Get 1:1 Help Now