SQLServer 2008 Merge语句的OUTPUT功能
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';
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!!
点击进行留言回复
相关文章:
-
-
sql某个日期是当年的第几周
/* *周一作为一周的开始 *当年的1月1号所在的周算作第一周 */ CREATE function GetWeekIndexFirstDate ( @...
[阅读全文]
-
-
数据库SQL---范式
1、数据冗余导致的问题:冗余存储、更新异常、插入异常、删除异常。 2、函数依赖:一种完整性约束。 在关系模式r(R)中,α属于R,β属于R。 1)α函数...
[阅读全文]
-
-
数据库SQL---查询
1、查询所有列 select *from emp;--*表示所有的,from emp表示从emp表中查询。 2、查询指定列 select empno,e...
[阅读全文]
-
-
-
-
-
网友评论