我需要从SQL Server 2008中的2个表中删除数据。
我有两个表A和B.我需要将每个表放在一个单独的事务中。
这是我正在使用的代码。
BEGIN TRANSACTION;
BEGIN TRY
DELETE from A
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
BEGIN TRANSACTION;
BEGIN TRY
DELETE from B
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
有没有更好的方法在SQL Server中实现多个事务和错误处理?
我需要为每个表添加单独的事务。
当其中一个交易失败时,我收到错误。
EXECUTE后的事务计数表示不匹配的数量 BEGIN和COMMIT语句。记录不会从其他记录中删除 交易
答案 0 :(得分:5)
试试这个:
BEGIN TRANSACTION;
BEGIN TRY
DELETE from A
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
END CATCH
BEGIN TRANSACTION;
BEGIN TRY
DELETE from B
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
END CATCH
答案 1 :(得分:0)
可能你可以这样做:
BEGIN TRANSACTION one;
BEGIN TRY
DELETE from A
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION one;
END CATCH
IF @@TRANCOUNT > 0
COMMIT TRANSACTION one;
BEGIN TRANSACTION two;
BEGIN TRY
DELETE from B
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION two;
END CATCH
IF @@TRANCOUNT > 0
COMMIT TRANSACTION two;