我写了一个像以下的交易:
BEGIN TRAN
UPDATE [Table1]
SET [Name] = 'abcd'
WHERE [ID] = 1
UPDATE [Table2]
SET [Product] = 'efgh'
WHERE [ID] = 10
UPDATE [Table3]
SET [Customar] = 'ijkl'
WHERE [ID] = 11
现在我想要回滚,如果任何UPDATE不成功。例如,在Table2中,如果没有ID = 10的Product,则应回滚事务。怎么做?请注意我正在使用SQLServer 2000.
答案 0 :(得分:5)
SQL Server 2000.如果使用SET XACT_ABORT ON
,则不需要回滚SET XACT_ABORT ON --to ensure rollback
BEGIN TRAN -- @@TRANCOUNT + 1
UPDATE [Table1]
SET [Name] = 'abcd'
WHERE [ID] = 1
IF @@ROWCOUNT = 0 ROLLBACK TRAN
IF @@TRANCOUNT > 0
BEGIN
UPDATE [Table2]
SET [Product] = 'efgh'
WHERE [ID] = 10
IF @@ROWCOUNT = 0 ROLLBACK TRAN
END
IF @@TRANCOUNT > 0
BEGIN
UPDATE [Table3]
SET [Customar] = 'ijkl'
WHERE [ID] = 11
IF @@ROWCOUNT = 0 ROLLBACK TRAN
END
IF @@TRANCOUNT > 0 COMMIT TRAN
答案 1 :(得分:1)
在每个UPDATE语句之前,您需要执行BEGIN TRAN并在每个UPDATE语句之后执行此操作 -
if @@Error > 0
THEN
BEGIN
ROLLBACK TRAN
END
Else
BEGIN
COMMIT TRAN
END