SQL 2008 T-SQL MERGE Operator

5 02 2009

I’ve had some opportunity to play around with a few of SQL 2008’s new features and I really like the new MERGE operator and wrote my own code sample.
-- create the source and target tables
declare @sourceTable table
(
id int primary key identity(1,1) not null,
firstName nvarchar(255) not null,
lastName nvarchar(255) not null
)

declare @targetTable table
(
id int primary key not null,
firstName nvarchar(255) not null,
lastName nvarchar(255) not null
)

-- populate the source
insert @sourceTable
select 'John', 'Doe' union
select 'Jane', 'Doe' union
select 'Adam', 'Smith' union
select 'Alex', 'Smith'

-- view the contents of both tables
select * from @sourceTable
select * from @targetTable

-- use the MERGE statement to populate the target from the source
merge @targetTable t -- target
using (select id, firstName, lastName from @sourceTable) s -- source
on t.id = s.id
when matched then update set t.firstName = s.firstName, t.lastName = s.lastName
when not matched by target then insert values (id, firstName, lastName)
when not matched by source then delete;

select * from @sourceTable
select * from @targetTable

-- Jane Doe and Alex Smith got married and Jane decided to hyphenate her last name to Doe-Smith
update @sourceTable set lastName = N'Doe-Smith'
where firstName = N'Jane' and lastName = N'Doe'

select * from @sourceTable
select * from @targetTable

-- source and target now have different values for the 3rd record
-- we can use the same code to match up target and source
merge @targetTable t -- target
using (select id, firstName, lastName from @sourceTable) s -- source
on t.id = s.id
when matched then update set t.firstName = s.firstName, t.lastName = s.lastName
when not matched by target then insert values (id, firstName, lastName)
when not matched by source then delete;

select * from @sourceTable
select * from @targetTable

-- remove Adam Smith from the source table
delete from @sourceTable where id = 1

select * from @sourceTable
select * from @targetTable

-- once again we'll use the same merge statment to match up our temporary source and target
merge @targetTable t -- target
using (select id, firstName, lastName from @sourceTable) s -- source
on t.id = s.id
when matched then update set t.firstName = s.firstName, t.lastName = s.lastName
when not matched by target then insert values (id, firstName, lastName)
when not matched by source then delete;

select * from @sourceTable
select * from @targetTable


Actions

Information

One response

5 02 2009
Roland

I just noticed that some of the doulbe dashes (-) for SQL comments is converted to a single — by WordPress. Just a heads up to change those to double dashes if the code is copied and pasted.

Leave a comment