Fork me on GitHub

T-Sql(二)事务(Transaction)

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

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

复制代码
 1 create database Transaction_9_30
 2 use Transaction_9_30
 3 drop table Zanghui
 4 create schema Jago 
 5 create table Jago.Zhanghui
 6 (
 7     ID int primary key,
 8     Balance int not null
 9 )
10 insert into Jago.Zhanghui(ID,Balance) values(1,1000);
11 insert into Jago.Zhanghui(ID,Balance) values(2,3000);
12 update Jago.Zhanghui set Balance=1000 where ID=1;
13 update Jago.Zhanghui set Balance=3000 where ID=2;
14 select *from Jago.Zhanghui
15 
16 begin transaction t1;                    --例子:转帐操作;一个表(id,balance)                               
17     declare @v bigint;                  --要求利用事务:
18     set @v = 0;
19     update Jago.Zhanghui set Balance=Balance-200 where ID=1;
20     if not exists(select *from Jago.Zhanghui where ID=1)
21         begin
22             --raiserror('asdfsdf',16,-1)
23             set @v = @v + 1;
24         end    
25     --set @v = @v + @@error;
26     print @v;
27     update Jago.Zhanghui set Balance=Balance+200 where ID=2;
28     if not exists(select *from Jago.Zhanghui where ID=2)
29         begin
30             --update Jago.Zhanghui set Balance=Balance+200 where ID=1;    
31             --raiserror('asdfsdf',16,-1)
32             set @v = 1;
33         end
34     
35     if(@v = 0)
36         begin
37             print @v
38             commit tran t1;
39         end
40     else
41         begin
42             print @v
43             rollback tran t1;
44         end
45 --commit transaction t1
46         
复制代码

 

posted @   田园里的蟋蟀  阅读(2137)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示