SQL Server 中SET XACT_ABORT設置的作用


SET XACT_ABORT

決定遇到runtime error的時候transaction能否繼續,大佬們都推薦設置為ON(參考文章末尾鏈接)。

沒有外部transaction 和 try...catch

簡單的例子如下:

--先創建測試表
IF OBJECT_ID('tb1') IS NOT NULL
DROP TABLE tb1
GO
CREATE table tb1(id int)
GO

設置為OFF

第一句執行出錯,仍然會繼續執行第二句,最后的select會得到結果1,同時會有error message "Divide by zero error encountered.".

SET XACT_ABORT OFF

INSERT INTO tb1 VALUES (1/0)    
INSERT INTO tb1 VALUES (1)    
select * from tb1

設置為ON

在第一個 insert語句就出錯了,后面的insert和select都不會執行。只有一個error message “Divide by zero error encountered.”

SET XACT_ABORT ON

INSERT INTO tb1 VALUES (1/0)    
INSERT INTO tb1 VALUES (2)    
select * from tb1

只有try...catch

示例代碼如下, 結果是不論On/Off都執行成功,返回數據集1

SET XACT_ABORT ON --OFF
GO
IF OBJECT_ID('tb1') IS NOT NULL
DROP TABLE tb1
GO
CREATE table tb1(id int)
GO

IF OBJECT_ID('pTestXactAbort') IS NOT NULL
DROP PROC pTestXactAbort
GO
create procedure pTestXactAbort
as
begin
	begin try
				raiserror('pTestXactAbort', 16,1)
	end try
	begin catch
		INSERT tb1(id) VALUES(1)
		select * from tb1
	end catch	
end
go


exec pTestXactAbort

有transaction和try...catch

示例代碼如下:


IF OBJECT_ID('tb1') IS NOT NULL
DROP TABLE tb1
GO
CREATE table tb1(id int)
GO

IF OBJECT_ID('pTestXactAbort') IS NOT NULL
DROP PROC pTestXactAbort
GO
create procedure pTestXactAbort
as
begin
	begin try
			begin transaction
				raiserror('pTestXactAbort', 16,1)
				
			commit transaction;
	end try
	begin catch
		INSERT tb1(id) VALUES(1)
		select * from tb1
		ROLLBACK TRAN
	end catch	
end
go

設置為OFF

執行成功的,得到結果“1”

在catch到error之后,catch部分仍然可以繼續執行其他的修改數據的代碼。

SET XACT_ABORT OFF
GO
exec pTestXactAbort

設置為ON

執行失敗並得到錯誤"The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction.".

SET XACT_ABORT ON
GO
exec pTestXactAbort

需要注意的是此時在catch中必須先rollback transaction,再處理其他操作。(如果只是select操作也不會出錯,但所有會寫數據庫transaction log的操作都會出錯)

如果把sp的定義中try...catch的部分改成先rollback tran,再處理其他操作就可以執行成功,如下:


IF OBJECT_ID('pTestXactAbort') IS NOT NULL
DROP PROC pTestXactAbort
GO
create procedure pTestXactAbort
as
begin
	begin try
			begin transaction
				raiserror('pTestXactAbort', 16,1)
				
			commit transaction;
	end try
	begin catch
		
		ROLLBACK TRAN
		INSERT tb1(id) VALUES(1)
		select * from tb1
	end catch	
end
go

默認設置

需要注意從不同應用程序生成的數據庫連接XACT_ABORT的默認設置是有可能不同的,曾經遇到過同一個sp同樣的參數在management studio中可以順利執行成功,但在應用程序中調用卻執行一半就出錯停止的問題。經調查就是因為management studio 中 XACT_ABORT默認設置為OFF,但程序里默認是ON。

參考鏈接


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM