gpt4 book ai didi

sql-server-2008 - 如何在 SQL Server 2008 中使用 MERGE 命令从源中删除?

转载 作者:行者123 更新时间:2023-12-03 10:26:06 28 4
gpt4 key购买 nike

我目前正在使用以下合并代码将日期从源迁移到目标。我有一个新要求,即扩展以下代码以在目标上执行更新/插入后从源中删除记录。这是否可以使用合并(我在网上看到的所有示例都在目标而不是源中执行了删除/插入/更新)

    MERGE Target1 AS T
USING Source1 AS S
ON (T.EmployeeID = S.EmployeeID)
WHEN NOT MATCHED BY TARGET AND S.EmployeeName LIKE 'S%'
THEN INSERT(EmployeeID, EmployeeName) VALUES(S.EmployeeID, S.EmployeeName)
WHEN MATCHED
THEN UPDATE SET T.EmployeeName = S.EmployeeName
WHEN NOT MATCHED BY SOURCE AND T.EmployeeName LIKE 'S%'
THEN DELETE ;

最佳答案

您可以使用 output 子句将修改/插入的行捕获到表变量中,并在合并后将其与删除语句一起使用。

DECLARE @T TABLE(EmployeeID INT);

MERGE Target1 AS T
USING Source1 AS S
ON (T.EmployeeID = S.EmployeeID)
WHEN NOT MATCHED BY TARGET AND S.EmployeeName LIKE 'S%'
THEN INSERT(EmployeeID, EmployeeName) VALUES(S.EmployeeID, S.EmployeeName)
WHEN MATCHED
THEN UPDATE SET T.EmployeeName = S.EmployeeName
WHEN NOT MATCHED BY SOURCE AND T.EmployeeName LIKE 'S%'
THEN DELETE
OUTPUT S.EmployeeID INTO @T;

DELETE Source1
WHERE EmployeeID in (SELECT EmployeeID
FROM @T);

关于sql-server-2008 - 如何在 SQL Server 2008 中使用 MERGE 命令从源中删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7331725/

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