Free Newsletters:
DatabaseJournal  
DBANews
Search Database Journal:
 
HOME News MS SQL Oracle DB2 Access MySQL PostgreSQL PHP SQL Etc Scripts Links Discussion
internet.com

» HOME
» NEWS
» FEATURES
» SERIES
MS SQL
Oracle
MS Access
MySQL
DB2
» RESOURCES
Products
Scripts
Links
» DISCUSSION
» TECH JOBS

Marketplace Partners
Be a Marketplace Partner




internet.commerce
Be a Commerce Partner
GPS
Desktop Computers
KVM over IP
Server Racks
Corporate Gifts
Online Education
Promote Your Website
Rackmount LCD Monitor
Condos For Sale
Web Hosting Directory
Shop Online
Remote Online Backup
KVM Switch over IP
Compare Prices




MySpace Joins eBay, Yahoo in Open Profile Push

News Corp. Unit Under Fire for Ties to Hacker

Are Non-PC Devices Hurting 'Net Innovation?

internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


Linked Data Planet Conference & Expo

CA ERwin® Data Modeler Proven database design and modeling. Efficiently analyze, design and deploy effective database solutions. Whitepaper: Manage SQL Server Deployments
Try it free: CA ERwin® Data Modeler

Access FREE HP Server Solutions Tools:
Access FREE HP Server Solutions Tools:
Whitepaper:
Continuous Real-time Data Protection and Disaster Recovery

Whitepaper:
Virtualization--It's Not Just for Enterprises Anymore

Whitepaper:
Rightsizing Blades for the Mid-market

Whitepaper:
VMware Infrastructure 3--Planning


Guide to Oracle 11g and Database Migration
Oracle Database 11g includes more features for self-management and automation, which makes it easier for customers to cost-effectively manage their data. Download this Internet.com eBook for an overview of some of the new features in 11g and for an overview of the issues you need to consider as you prepare for a database migration. »
Innovate Faster with Oracle Database 11g
Read this in-depth analysis of 56 customers, which shows significant differences between the value software vendors Oracle and SAP deliver to midsize companies. »
Oracle Business Intelligence Standard Edition One
Find out how Newport Beach, CA-based Mobilitie is shaking up the telecom industry by leveraging technology to provide an entirely different financial model for deploying, upgrading, and owning wireless and wireline network assets. »
Business Intelligence and Enterprise Performance Management: Trends for Emerging Businesses
Quickly implementing an ERP software solution can be of tremendous benefit; however, companies often struggle to balance the benefits of reducing implementation time and cost with the risks of an accelerated deployment. Read this white paper to learn about easy-to-follow best practices for achieving a successful accelerated implementation. »
Making the Case for Oracle Database on Windows
Users benefit as vendors reduce enterprise complexity and deliver integration. »

Production Manager (hands on)
Aquent
US-MA-Cambridge

Justtechjobs.com Post A Job | Post A Resume
MS SQL
April 16, 2008
UPSERT Functionality in SQL Server 2008
By Muthusamy Anantha Kumar aka The MAK

The UPSERT command inserts rows that don’t exist and updates the rows that do exist. The Word UPSERT is a fusion of the words UPDATE and INSERT. UPSERT was officially introduced in the SQL:2003 standard.

IF FOUND
   THEN UPDATE
ELSE
   INSERT;

In SQL Server 2008, Microsoft introduces the UPSERT functionality through the MERGE command.

Until now, this UPSERT functionality could only be made available in SQL Server through stored procedures and cursors, etc.

This article illustrates how to take advantage of the UPSERT functionality via the MERGE command.

Note: This article is written based on SQL Server 2008 CTP6.

Step 1

Let’s assume that we have a database [MyDatabase] as shown below. [Refer Fig 1.0]

USE [master]
GO
/****** Object:  Database [MyDatabase]    Script Date: 03/16/2008 10:55:35 ******/
IF  EXISTS (SELECT name FROM sys.databases WHERE name = N'MyDatabase')
DROP DATABASE [MyDatabase]
GO
create database [MyDatabase]
go


Fig 1.0

Step 2

Let’s assume that we have the following three tables, as shown below. [Refer Fig 1.1]

USE [MyDatabase]
GO
 
/****** Object:  Table [dbo].[MyTable]    Script Date: 03/16/2008 11:07:24 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MyTable]') AND type in (N'U'))
DROP TABLE [dbo].[MyTable]
GO
 
create table MyTable (id int primary key, name varchar(100),salary money)
go
insert into MyTable select 1,'Catherine Donnel',200000
insert into MyTable select 2,'Stacey Kost',150000
insert into MyTable select 3,'Jason Leanos',36000
insert into MyTable select 4,'Catherine O''Donnel',20000
insert into MyTable select 5,'Rainbow Dance',20000
 
go
USE [MyDatabase]
GO
 
/****** Object:  Table [dbo].[MyTable2]    Script Date: 03/16/2008 11:07:36 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MyTable2]') AND type in (N'U'))
DROP TABLE [dbo].[MyTable2]
GO
 
 
create table MyTable2 (id int primary key, name varchar(100),salary money)
go
insert into MyTable2  select 1,'Catherine O''Donnel',220000
insert into MyTable2 select 2,'Stacey Kostue',230000
insert into MyTable2 select 4,'Catherine Bonaparte',20000
insert into MyTable2 select 9,'Irina Zolotrova',40000
insert into MyTable2 select 5,'Eva Jane',40034
go


Fig 1.1

Step 3

Now let’s query both of the tables to see the difference between them.

USE [MyDatabase]
GO
Select * from MyTable
Go
Results:
id, name, salary
1, Catherine Donnel, 200000.00
2, Stacey Kost, 150000.00
3, Jason Leanos, 36000.00
4, Catherine O'Donnel, 20000.00
5, Rainbow Dance, 20000.00
 
(5 row(s) affected)
USE [MyDatabase]
GO
Select * from MyTable2
GO

Results:

id, name, salary
1, Catherine O'Donnel, 220000.00
2, Stacey Kostue, 230000.00
4, Catherine Bonaparte, 20000.00
5, Eva Jane, 40034.00
9, Irina Zolotrova, 40000.00
 
(5 row(s) affected)

From the results, we can easily understand that if we want to merge all of the rows from Mytable2 to Mytable, then the following updates and following inserts are supposed to be executed. [Refer Fig 1.2]


Fig 1.2

Step 4

Now let’s UPSERT the table by using the following merge command to merge the content of the table Mytable2 to the table Mytable. [Refer Fig 1.3]

USE [MyDatabase]
GO
merge into mytable as Target
using mytable2 as Source
on Target.id=Source.id
when matched then 
update set Target.name=Source.name,
Target.Salary = Source.Salary
when not matched then
insert (id,name,salary) values (Source.id,Source.name,Source.Salary);


Fig 1.3

Step 5

Now let’s query the target table, MyTable, as shown below. [Refer Fig 1.4]

USE [MyDatabase]
GO
Select * from MyTable
GO

Results:

id, name, salary
1, Catherine O'Donnel, 220000.00
2, Stacey Kostue, 230000.00
3, Jason Leanos, 36000.00
4, Catherine Bonaparte, 20000.00
5, Eva Jane, 40034.00
9, Irina Zolotrova, 40000.00
 
(6 row(s) affected)


Fig 1.4

From the results, we see that all of the existing rows in the table, Mytable, have been updated with the data from the table, Mytable2. In addition, we see that any new rows that were present in the Mytable2 table have been inserted to the table, MyTable.

Basically, the merge command executed the following algorithm.

Note: The below syntax is not a transact SQL command. It is just an algorithm.

If target.ID = 1 is found in Source.id = 1 {found}
then
update target 
set target.name {Catherine Donnel} = source.name  {Catherine O''Donnel}
Target.salary {200000}=Source.salary {220000}
end if
 
If target.ID = 2 is found in Source.id = 2 {found}
then
update target 
set target.name {Stacey Kost} = source.name  {Stacey Kostue}
Target.salary {150000.00} = Source.salary {230000.00}
end if
 
If target.ID=3 is found in Source.Id = NULL {not found}
 then
 
end if
 
If target.ID=4 is found in Source.id = 4 {found}
then
update target 
set target.name {Catherine O''Donnel} = source.name  {Catherine Bonaparte}
Target.salary {20000.00} = Source.salary {20000.00}
end if
 
If target.ID=5 is found in Source.id = 5 {found}
then
update target 
set target.name {Rainbow Dance} = source.name  {Eva Jane}
Target.salary {20000.00} = Source.salary {40034.00}
end if
 
If target.ID not found in Source.id = 9 {found}
then
insert into target (id,name,salary) select source (9, Irina Zolotrova, 40000.00)
 
end if

Conclusion

This article has illustrated the functionality of UPSERT via the MERGE command in SQL Server 2008.

» See All Articles by Columnist MAK

Tools:
Add databasejournal.com to your favorites
Add databasejournal.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed

MS SQL Archives

Whitepaper: Enterprise Information Integration--Deployment Best Practices for Low-Cost Implementation
Flash Demo: Learn how IBM Information Server Blade is easy to manage, highly scalable and efficient.
Download: Solaris 8 Migration Assistant. Run Solaris 8 apps on the latest SPARC systems and Solaris 10.
IT in 2018: Download Free eBook By The Author Of "Does IT Matter?" Simple Registration Is Required.
Five Trends for Application Development. Download Your Complimentary Report. Exclusive. Act Now.


Latest Forum Threads
MS SQL Forum
Topic By Replies Updated
How To Transfer Access Data Records To SQL ?? ankurdjariwala 1 May 8th, 12:24 PM
problem with federated server linking majidkhan 1 April 29th, 10:00 AM
"SELECT rowguidcol" from tables on linked servers? brentbordelon 1 April 25th, 04:12 PM
"SELECT rowguidcol" vs. "SELECT <actual name>" rgarrison 9 April 16th, 03:46 PM







JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES