我有一个临时表,用于快速插入许多数据。然后我使用SQL合并将临时表中的数据插入主表(目标表)。但是我想在插入目标表后立即从源表中删除每条记录。类似下面的代码:
MERGE Target AS T
USING Source 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)
--THEN DELETE INSERTED ITEM------------------------------
WHEN MATCHED
THEN UPDATE SET T.EmployeeName = S.EmployeeName
WHEN NOT MATCHED BY SOURCE AND T.EmployeeName LIKE 'S%'
THEN DELETE
答案 0 :(得分:1)
与documentation一样,合并"根据与源表"的连接结果,对目标表执行插入,更新或删除操作
您是否只能在合并后添加删除语句以删除临时表中存在的原始表中的行?
答案 1 :(得分:1)
我想在插入后立即从源表中删除每条记录 进入目标表。
在大多数情况下,在RDBMS中,您可以将其改为
我想在INSERT / UPDATE
的同一事务中删除源表中的记录
所以我建议的方法是:
BEGIN TRANSACTION
MERGE Target AS T
USING Source 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)
--THEN DELETE INSERTED ITEM------------------------------
WHEN MATCHED
THEN UPDATE SET T.EmployeeName = S.EmployeeName
WHEN NOT MATCHED BY SOURCE AND T.EmployeeName LIKE 'S%'
THEN DELETE
OUTPUT inserted.EmployeeID INTO #TempTable
DELETE FROM Source
WHERE EmployeeID IN (SELECT EmployeeID FROM #TempTable)
COMMIT TRANSACTION