sqlserver中创建包含事务的存储过程

 2023-09-10 阅读 15 评论 0

摘要:什么是事务 事务时包含1条或多条语句的逻辑单元。事务中的语句是一个整体,要么一起提交,要么一起撤销。事务在提交前可以回滚,一旦提交就不能撤销修改了,是永久性的修改。 为什么使用事务 可以例举生活中的例子,比如银行转账:A向B
什么是事务
事务时包含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 int3 as4 begin5 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 int3 as4 begin5 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

转载于:https://www.cnblogs.com/zxtceq/p/5956813.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/37602.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息