在SQL Server 2008r2上,我们有一个如下所示的存储过程:
create procedure x(@arg1 as nvarchar(20), @arg2 ... )
as
begin
-- delete and insert values, depending on arguments
begin transaction;
delete from tblA where f1 = @arg1 ... ;
insert into tblB (a) select ... where f2 = @arg2 ... ;
commit transaction;
end;
我使用SqlCommand.ExecuteNonQuery()
方法在C#(.NET 4.5)中调用此过程。
try--- catch
现在在这个方法的文档中,它说“如果发生回滚,返回值为-1。”
问题:是否可以在没有异常的情况下发生回滚?
到目前为止,如果无法执行sql语句,我们总是会遇到异常。但是,是否会出现“自动”回滚而不抛出异常的情况?
答案 0 :(得分:1)
您能否看看 gbn的答案,交易模板 Nested stored procedures containing TRY CATCH ROLLBACK pattern?
基于你的问题,我已经修改了程序,以便在发生回滚时返回-1。
CREATE PROCEDURE [Name]
@arg1 as nvarchar(20),
@arg2 as nvarchar(20)
AS
SET XACT_ABORT, NOCOUNT ON
DECLARE @starttrancount int
BEGIN TRY
SELECT @starttrancount = @@TRANCOUNT
IF @starttrancount = 0
BEGIN TRANSACTION
delete from tblA where f1 = @arg1 ... ;
insert into tblB (a) select ... where f2 = @arg2 ... ;
IF @starttrancount = 0
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 AND @starttrancount = 0
BEGIN
ROLLBACK TRANSACTION
RETURN -1
END
END CATCH
GO