SQL 事务处理

来源:互联网 发布:mac电脑壁纸文件夹 编辑:程序博客网 时间:2024/05/22 13:07
 
--建表create table tns(id int identity not null,names varchar(50) not null,age int not null check(age<25),guid varchar(50) not null default(newid()),primary key(id),)-- 删除表drop table tns--插入数据declare @count intset @count=0while(@count<=20)begininsert into tns(names,age) values('Tom'+cast(@count as varchar),@count)set @count=@count+1endselect * from tns--事务具有一致性,在事务里面的操作要么全部完成要么全部失败/*格式begin transactionSQL语句end全局错误变量@error它能捕捉上次执行语句出现的错误号,若无错误则返回0应用:如向1个表插入10条数据,但当插入到第8条时出错了,但此时已经插入了8条了这就可以通过事务来达到操作处理的一致性*/begin transactiondeclare @counts intdeclare @errors intset @counts=0set @errors=0while(@counts<=30)begininsert into tns(names,age)values('Jim'+cast(@counts as varchar),@counts)set @errors=@errors+@@error--捕捉错误set @counts=@counts+1--自增endif(@errors=0)--若无错误则提交事务begincommit--提交事务print '事务全部处理完成'endelsebeginrollback--撤销事务print '出错了,事务已经回滚'endselect * from tns--查询delete tns--删除表数据

原创粉丝点击