参考2:【SQL Server学习笔记】Delete 语句、Output 子句、Merge语句
功能需求:将A表状态为0的数据导入到B表,并将A表的状态更改为1
-- 表A CREATE TABLE TABLEA (ID INT ,STATE INT) -- 表B CREATE TABLE TABLEB (ID INT) -- 添加测试数据 INSERT TABLEA (ID, STATE) VALUES (1,0); INSERT TABLEA (ID, STATE) VALUES (2,0); INSERT TABLEA (ID, STATE) VALUES (3,0); -- 临时表保存受影响的行ID DECLARE @TmpTable TABLE (ID INT) -- 使用Merge 将A表数据导入B表 并将受影响行插入临时表 MERGE INTO TABLEB AS t USING TABLEA AS s ON t.ID=s.ID WHEN NOT MATCHED THEN INSERT (ID) VALUES (s.ID) OUTPUT Inserted.ID INTO @TmpTable; -- 将A表受影响行状态修改为1 UPDATE t1 SET t1.STATE = 1 OUTPUT inserted.ID FROM TABLEA t1 INNER JOIN @TmpTable t2 ON t1.ID = t2.ID;