我想知道如果我不能插入,是否有办法回滚删除。
请指教。
像下面的东西。
BEGIN TRAN
Delete from MYTABLE where ID=@ID;
INSERT INTO MYTABLE (ID, NAME)
SELECT @ID, NAME
COMMIT
我想知道如果我不能插入,是否有办法回滚删除。
请指教。
像下面的东西。
BEGIN TRAN
Delete from MYTABLE where ID=@ID;
INSERT INTO MYTABLE (ID, NAME)
SELECT @ID, NAME
COMMIT
您可以将两个语句放入一个TRY....CATCH
块中,并且仅在两个语句都成功时才提交:
BEGIN TRANSACTION
BEGIN TRY
DELETE FROM dbo.MYTABLE WHERE ID=@ID;
INSERT INTO dbo.MYTABLE (ID, NAME)
SELECT @ID, NAME
-- COMMIT only if both DELETE and INSERT worked ....
COMMIT TRANSACTION
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage
-- ROLLBACK if either DELETE and INSERT failed ....
ROLLBACK TRANSACTION
END CATCH
打开xact_abort以在出现任何错误时回滚事务。
SET XACT_ABORT ON;
BEGIN TRAN
Delete from MYTABLE where ID=@ID;
INSERT INTO MYTABLE (ID, NAME)
SELECT @ID, NAME
COMMIT TRAN
这是完成您似乎正在尝试的另一种方法:
update myTable
set name = @name
where id = @id
BEGIN TRAN
Delete from MYTABLE where ID=@ID;
INSERT INTO MYTABLE (ID, NAME)
SELECT @ID, NAME
if @@error = 0 and @@trancount > 0
commit
else
rollback