在 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;
我在 C# (.NET 4.5) 中使用 SqlCommand.ExecuteNonQuery()
方法调用此过程。
所有异常都被 try---catch
现在在这个方法的文档中,它说“如果发生回滚,返回值为-1。”
问题:会不会没有得到异常就回滚了?
到目前为止,如果 sql 语句无法执行,我们总是会遇到异常。但是会不会出现回滚“自动”发生而不抛出异常的情况?
最佳答案
你能看看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
关于c# - 回滚而不抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19144492/