欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQLServer 2008 Merge语句的OUTPUT功能

程序员文章站 2022-05-28 12:17:40
下面介绍一下把output同2008的新t-sql语句merge组合使用的方法: 新建下面表:复制代码 代码如下:create table book( isbn varch...
下面介绍一下把output同2008的新t-sql语句merge组合使用的方法:
新建下面表:
复制代码 代码如下:

create table book(
isbn varchar(20) primary key,
price decimal,
shelf int)

create table weeklychange(
isbn varchar(20) primary key,
price decimal,
shelf int)

create table bookhistory(
action nvarchar(10),
newisbn varchar(20),
newprice decimal,
newshelf int,
oldisbn varchar(20),
oldprice decimal,
oldshelf int,
archivedat datetime2)

sql语句为
复制代码 代码如下:

merge book as b
using weeklychange as wc
on b.isbn = wc.isbn
when matched and (b.price <> wc.price or b.shelf <> wc.shelf) then
update set b.price = wc.price, b.shelf = wc.shelf
when not matched then
insert values(wc.isbn, wc.price, wc.shelf)
output $action, inserted.*, deleted.*, sysdatetime()
into bookhistory;

结果集为:

select * from bookhistory
go

action newisbn newprice newshelf oldisbn oldprice oldshelf archivedat
------ ------- -------- -------- ------- -------- -------- ---------------------------
update a 101 1 a 100 1 2007-11-25 14:47:23.9907552
insert c 300 3 null null null 2007-11-25 14:47:23.9907552

这里有insert和update两种output情况。如果只需要其中一种,可以用下面这种方法过滤:
复制代码 代码如下:

insert into book(isbn, price, shelf, archivedat)
select isbn, price, shelf, getdate() from
(merge book as b
using weeklychange as wc
on b.isbn = wc.isbn and b.archivedat is null
when matched and (b.price <> wc.price or b.shelf <> wc.shelf) then
update set price = wc.price, shelf = wc.shelf
when not matched then
insert values(wc.isbn, wc.price, wc.shelf, null)
output $action, wc.isbn, deleted.price, deleted.shelf
) changes(action, isbn, price, shelf)
where action = 'update';