Solved

query to insert or update

Posted on 2015-02-02
3
85 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

What Is Blockchain Technology?

Blockchain is a technology that underpins the success of Bitcoin and other digital currencies, but it has uses far beyond finance. Learn how blockchain works and why it is proving disruptive to other areas of IT.

Question has a verified solution.

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

In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
Via a live example, show how to take different types of Oracle backups using RMAN.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

622 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