Solved

query to insert or update

Posted on 2015-02-02
3
83 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 500 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

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Upgrading my SSIS package in VS 2012 6 61
oracle forms question 22 42
Get Next number from Stored Procedure 8 23
setting local variables in a cursor block 3 20
Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

830 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