SQLSERVER 儲存過程 事務 小結

2021-06-27 11:15:54 字數 3170 閱讀 5378

sqlserver 事務

在儲存過程中使用事務的時候也遇到些概念性的錯誤和操作性的錯誤,特記錄下來。

提到事務,一般都知道其是乙個單個的工作單元,也就是使用者定義的乙個操作序列,要麼都成功,要麼都失敗。

事務有乙個  隱藏的 xact_abort 設定開關,一般在啟用事務(transaction)的時候,其預設值為off

xact_abort 官方給的解釋是 「指定當 transact-sql 語句出現執行時錯誤時,sql server 是否自動回滾當前事務」

其中當 set xact_abort 為 on 時,如果執行 transact-sql 語句產生執行時錯誤,則整個事務將終止並回滾。

當 set xact_abort 為 off 時,有時只回滾產生錯誤的 transact-sql 語句,而事務將繼續進行處理。 如果錯誤很嚴重,那麼即使 set xact_abort 為 off,也可能回滾整個事務。 off 是預設設定。

第一種:

我在使用事務的時候,犯得第乙個錯誤時,錯誤理解使用到呢系統給的函式@@error

例如:create table student

create procedure pro_student_test

asbegin tran

insert into student(name,age) values('中國人民a',null);

insert into student(name,age) values('中國人民共和國,中國人名共和國',null);  --插入name,字元超過定義大小

insert into student(name,age) values('中國人民b',null);

if @@error <> 0

rollback tran

else

commit tran

endgo

@@error :返回執行的上乙個 transact-sql 語句的錯誤號。如果最後的 transact-sql 語句執行成功,則 @@error 系統函式返回 0,其中每乙個 transact-sql 語句完成時,@@error 的值都會改變。

上面乙個儲存過程錯誤點就在於判斷的依據是最後乙個語句返回的@error,結果是第一條和第三條都插入到資料中,而沒有出現當發生錯誤的時候整個操作系列都回滾的現象

結果插入1

插入2

第二種情況:如果開啟呢 xact_abort 為on 的話

create procedure pro_student_test

asset xact_abort on

begin tran

insert into student(name,age) values('中國人民a',null);

insert into student(name,age) values('中國人民共和國,中國人名共和國',null);  --插入name,字元超過定義大小

insert into student(name,age) values('中國人民b',null);

commint tran

endgo

結果:第二條語句發生錯誤,整個事務都回滾。

插入結果3

插入結果4

第三種情況:如果沒有開啟 xact_abort 也就是不寫這個屬性和顯示設定為off的話

create procedure pro_student_test

asset xact_abort off --(不寫這條語句或者顯示設定成off)

begin tran

insert into student(name,age) values('中國人民a',null);

insert into student(name,age) values('中國人民共和國,中國人名共和國',null);  --插入name,字元超過定義大小

insert into student(name,age) values('中國人民b',null);

commint tran

endgo

結果:第二天語句發生錯誤,第二天語句自身回滾,第一條和第三條都插入到資料庫中

結果插入5,

結果插入6

第四種 :如果沒有開啟 xact_abort 但結合try catch 進行捕獲

create procedure pro_student_test

asbegin try

begin tran

insert into student(name,age) values('中國人民a',null);

insert into student(name,age) values('中國人民共和國,中國人名共和國',null);  --插入name,字元超過定義大小

insert into student(name,age) values('中國人民b',null);

commint tran

return 1    

end try

begin catch

rollback tran

return 0

end catch

endgo

結果:遇到第二天語句發生錯誤的時候,整個事務都回滾

結果插入7

結果插入8

第二種顯示開啟 xact_abort 為on 和使用到呢try catch 的都可以使整個事務發生回滾。

推薦使用第二種,少寫**。

Sql server 事務 儲存過程

事務 transaction 是併發控制的單位,是使用者定義的乙個操作序列。這些操作要麼都做,要麼都不做,是乙個不可分割的工作單位。通過事務,sql server 能將邏輯相關的一組操作繫結在一起,以便伺服器保持資料的完整性。在 sql server net 開發環境下,有兩種方法能夠完成事務的操作...

SQLserver 表變數 事務 儲存過程

在t sql中使用變數 一 區域性變數 1宣告變數 age和 name declare age int declare name nvarchar 5 2賦值 1 方法1 set age 18 set name 張飛 2 方法2 select age 18 select name 張飛 3分別使用s...

sql server儲存過程回滾事務

set nocount on這個很常用 作用 阻止在結果集中返回顯示受t sql語句或則usp影響的行計數資訊。當set oncount on時候,不返回計數,當set nocount off時候,返回計數 即使當set nocount on 時候,也更新 rowcount 當set nocount...