sqlserver中創建包含事務的存儲過程


什么是事務
    事務時包含1條或多條語句的邏輯單元。事務中的語句是一個整體,要么一起提交,要么一起撤銷。事務在提交前可以回滾,一旦提交就不能撤銷修改了,是永久性的修改。
 
為什么使用事務
    可以例舉生活中的例子,比如銀行轉賬:A向B轉100萬。程序的執行順序:1.A賬戶減掉100萬 2.B賬戶增加100萬。若是都成功執行倒沒什么,假設1成功執行,2執行失敗,就會出問題。運用事務就不會出現這種問題,因為只要其中有一步操作失敗,事務就會回滾,之前的所有操作將會被撤銷。
 
事務的基本控制語句
1.BEGIN TRANSACTION:事務開始
2.COMMIT TRANSACTION:事務提交
3.ROLLBACK TRANSACTION:事務回滾
 
事務的特性(ACID)
1.ATOMIC(原子性):事務中程序是數據庫的邏輯工作單元,對數據的修改要么全執行,要么全不執行。
2.CONSISTENT(一致性):事務執行前后數據一致,事務完成之后數據的修改才可見。
3.ISOLATED(隔離性):並發事務之間不能相互干擾
4.DURABLE(持久性):事務一旦提交就是對數據的永久修改。
  
下面是一個包含事務的存儲過程的例子:
 1 ALTER proc [dbo].[Proc_InsertStudent]
 2 @stuName nvarchar(50),@stuClassId int,@stuAge int
 3 as
 4 begin
 5 set nocount on  --on表示不返回計數
 6 set xact_abort on  --當執行事務時,如果出錯,會將transcation設置為uncommittable狀態
 7 
 8 begin try 
 9 declare @stuCountByName int;
10 select @stuCountByName=count(*) from Students where Name=@stuName;
11 
12 if(isnull(@stuName,'')='')
13 begin
14 print('名字不能為空');
15 return;
16 end
17 
18 if(@stuCountByName>0)
19 begin
20 print('名字重復');
21 return
22 end
23 
24 begin tran  --開啟事務
25 insert into Students(Name,ClassId,Age) values(@stuName,@stuClassId,@stuAge)
26 commit tran  --提交事務
27 
28 end try
29 
30 begin catch
31 if xact_state()=-1
32 rollback tran;  --回滾事務
33 select ERROR_NUMBER() as ErrorNumber;
34 select ERROR_MESSAGE() as ErrorMsg;
35 end catch
36 set xact_abort off;
37 end

其中Students表:
1 CREATE TABLE [dbo].[Students](
2  [ID] [int] IDENTITY(1,1) NOT NULL primary key,
3  [Name] [nvarchar](50) NOT NULL,
4  [ClassId] [int] NOT NULL,
5  [Age] [int] NOT NULL,
6  [CreateTime] [datetime] NOT NULL
7 );
復制代碼



















復制代碼
 1 ALTER proc [dbo].[Proc_InsertStudent]
 2 @stuName nvarchar(50),@stuClassId int,@stuAge int
 3 as
 4 begin
 5 set nocount on  --on表示不返回計數
 6 set xact_abort on  --當執行事務時,如果出錯,會將transcation設置為uncommittable狀態
 7 
 8 begin try 
 9 declare @stuCountByName int;
10 select @stuCountByName=count(*) from Students where Name=@stuName;
11 
12 if(isnull(@stuName,'')='')
13 begin
14 print('名字不能為空');
15 return;
16 end
17 
18 if(@stuCountByName>0)
19 begin
20 print('名字重復');
21 return
22 end
23 
24 begin tran  --開啟事務
25 insert into Students(Name,ClassId,Age) values(@stuName,@stuClassId,@stuAge)
26 commit tran  --提交事務
27 
28 end try
29 
30 begin catch
31 if xact_state()=-1
32 rollback tran;  --回滾事務
33 select ERROR_NUMBER() as ErrorNumber;
34 select ERROR_MESSAGE() as ErrorMsg;
35 end catch
36 set xact_abort off;
37 end


免責聲明!

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



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