query to insert or update

Posted on 2015-02-02
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.
Question by:shwelopo

Expert Comment

by:Monika Bharti
ID: 40585573

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)
     THEN INSERT(product, something) VALUES(S._product, S.something)
     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.
LVL 142

Accepted Solution

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:

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

Cursors in Oracle: A cursor is used to process individual rows returned by database system for a query. In oracle every SQL statement executed by the oracle server has a private area. This area contains information about the SQL statement and the…
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
This video shows syntax for various backup options while discussing how the different basic backup types work.  It explains how to take full backups, incremental level 0 backups, incremental level 1 backups in both differential and cumulative mode a…
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

813 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