gpt4 book ai didi

sql-server - T-SQL MERGE - 找出它采取了哪些操作

转载 作者:行者123 更新时间:2023-12-03 00:27:01 24 4
gpt4 key购买 nike

我需要知道 MERGE 语句是否执行了 INSERT。在我的场景中,插入是 0 或 1 行。

测试代码:

DECLARE @t table (C1 int, C2 int)
DECLARE @C1 INT, @C2 INT

set @c1 = 1
set @c2 = 1

MERGE @t as tgt
USING (SELECT @C1, @C2) AS src (C1, C2)
ON (tgt.C1 = src.C1)
WHEN MATCHED AND tgt.C2 != src.C2 THEN
UPDATE SET tgt.C2 = src.C2
WHEN NOT MATCHED BY TARGET THEN
INSERT VALUES (src.C1, src. C2)
OUTPUT deleted.*, $action, inserted.*;

SELECT inserted.*

最后一行无法编译(没有作用域,与触发器不同)。我无法访问@action 或输出。实际上,我不需要任何输出元数据。

我该怎么做?

最佳答案

您可以输出到表变量中,然后从中检索。试试这个:

DECLARE @t table (C1 int, C2 int)
DECLARE @C1 INT, @C2 INT
DECLARE @Output TABLE (DeletedC1 INT, DeletedC2 INT, ActionType VARCHAR(20), InsertedC1 INT, InsertedC2 INT)

set @c1 = 1
set @c2 = 1

MERGE @t as tgt
USING (SELECT @C1, @C2) AS src (C1, C2)
ON (tgt.C1 = src.C1)
WHEN MATCHED AND tgt.C2 != src.C2 THEN
UPDATE SET tgt.C2 = src.C2
WHEN NOT MATCHED BY TARGET THEN
INSERT VALUES (src.C1, src. C2)
OUTPUT deleted.*, $action, inserted.* INTO @Output;

SELECT * FROM @Output WHERE ActionType = 'INSERT'

关于sql-server - T-SQL MERGE - 找出它采取了哪些操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4507444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com