当前位置: 移动技术网 > IT编程>数据库>MSSQL > SQLServer 2008 Merge语句的OUTPUT功能

SQLServer 2008 Merge语句的OUTPUT功能

2017年12月08日  | 移动技术网IT编程  | 我要评论

mp3dj舞曲,余额宝多久有收益,喊麦词大全

下面介绍一下把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';

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网