T-Sql(二)事务(Transaction)

时间:2023-03-09 16:18:38
T-Sql(二)事务(Transaction)

  今天讲下T-Sql语法中事务的用法,事务在项目中一般用的很少,主要用于转账,或是一些多表操作,第一步完成不了滚回,不执行接下的步骤。要么都不完成要么都完成,这是事务的特征。

  语法很简单,示例代码如下:

 create database Transaction_9_30
use Transaction_9_30
drop table Zanghui
create schema Jago
create table Jago.Zhanghui
(
ID int primary key,
Balance int not null
)
insert into Jago.Zhanghui(ID,Balance) values(1,1000);
insert into Jago.Zhanghui(ID,Balance) values(2,3000);
update Jago.Zhanghui set Balance=1000 where ID=1;
update Jago.Zhanghui set Balance=3000 where ID=2;
select *from Jago.Zhanghui begin transaction t1; --例子:转帐操作;一个表(id,balance)
declare @v bigint; --要求利用事务:
set @v = 0;
update Jago.Zhanghui set Balance=Balance-200 where ID=1;
if not exists(select *from Jago.Zhanghui where ID=1)
begin
--raiserror('asdfsdf',16,-1)
set @v = @v + 1;
end
--set @v = @v + @@error;
print @v;
update Jago.Zhanghui set Balance=Balance+200 where ID=2;
if not exists(select *from Jago.Zhanghui where ID=2)
begin
--update Jago.Zhanghui set Balance=Balance+200 where ID=1;
--raiserror('asdfsdf',16,-1)
set @v = 1;
end if(@v = 0)
begin
print @v
commit tran t1;
end
else
begin
print @v
rollback tran t1;
end
--commit transaction t1