SQL:删除并插入一个存储过程

时间:2015-01-20 06:25:07

标签: sql sql-server stored-procedures sql-update sql-delete

我希望删除查询在开头只执行一次。执行insert语句之后,直到所有数据都成功保存在DB中。

1 个答案:

答案 0 :(得分:1)

尝试使用MERGE语句

- 正确指定了连接条件的MERGE语句。

USE tempdb;
GO
BEGIN TRAN;
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)
WHEN MATCHED 
    THEN UPDATE SET T.EmployeeName = S.EmployeeName
WHEN NOT MATCHED BY SOURCE AND T.EmployeeName LIKE 'S%'
    THEN DELETE 
OUTPUT $action, inserted.*, deleted.*;
ROLLBACK TRAN;
GO