[英]How to retrieve old values in OUTPUT clause with SQL MERGE statement
I'm using MERGE statement to update a product table containing (Name="a", Description="desca")
.我正在使用 MERGE 语句来更新包含
(Name="a", Description="desca")
的产品表。 My source table contains (Name="a", Description="newdesca")
and I merge on the Name field.我的源表包含
(Name="a", Description="newdesca")
并且我在名称字段上合并。
In my Output clause, I would like to get back the field BEFORE the update -> Description = "desca"
.在我的输出子句中,我想在更新之前取回该字段 ->
Description = "desca"
。
I couldn't find a way to do that, I'm always getting back the new value ("newdesca")
.我找不到办法做到这一点,我总是取回新值
("newdesca")
。 Why?为什么?
Can you not just used the deleted
memory-resident table.你能不能只使用
deleted
的内存驻留表。 eg:例如:
IF OBJECT_ID(N'tempdb..#T', 'U') IS NOT NULL
DROP TABLE #T;
CREATE TABLE #T (Name VARCHAR(5), Description VARCHAR(20));
INSERT #T (Name, Description)
VALUES ('a', 'desca'), ('b', 'delete');
MERGE #T AS t
USING (VALUES ('a', 'newdesca'), ('c', 'insert')) AS m (Name, Description)
ON t.Name = m.Name
WHEN MATCHED THEN
UPDATE SET Description = m.Description
WHEN NOT MATCHED BY TARGET THEN
INSERT (Name, Description)
VALUES (m.Name, m.Description)
WHEN NOT MATCHED BY SOURCE THEN
DELETE
OUTPUT $Action, inserted.*, deleted.*;
IF OBJECT_ID(N'tempdb..#T', 'U') IS NOT NULL
DROP TABLE #T;
The output of this would be:其输出将是:
$Action | Name | Description | Name | Description
--------+-------+-------------+------+--------------
INSERT | c | insert | NULL | NULL
UPDATE | a | newdesca | a | desca
DELETE | NULL | NULL | b | delete
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.