您的位置:首页 > 数据库

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

2016-10-13 16:04 507 查看
什么是事务
事务时包含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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐