SQLServer 2008 Merge语句的OUTPUT功能

编程学习 2021-07-05 16:15www.dzhlxh.cn编程入门
SQL Server 2005中的Output功能可以把Insert,Update和Delete的内容都返回,2008中的Output同样具有此功能
狼蚁网站SEO优化介绍一下把Output同2008的新T-SQL语句Merge组合使用的方法:
新建狼蚁网站SEO优化表:
代码如下:

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情况。如果只需要其中一种,可以用狼蚁网站SEO优化这种方法过滤:
代码如下:

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';

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板