关于事务,存储过程,触发器的简单例子
2012-08-13 01:48
337 查看
用一个简单的Bank表分别对事务,存储过程和触发器写个简单例子
Bank表有连个字段:Id(账号)varchar(4);
Balance(账号金额)money (check约束 Balance>10)
1.事务(转账)
使用try-catch)(减少代码量)
2存储过程(转账)
3.触发器-(如果给任何账户打钱,都会把钱打到'0004'这个账号)(instead of)还有另一种触发器after(写for默认是after)
Bank表有连个字段:Id(账号)varchar(4);
Balance(账号金额)money (check约束 Balance>10)
1.事务(转账)
begin transaction declare @error int; set @error=0; update bank set Balance=Balance-1000 where Id='0001'; set @error=@error+@@ERROR; update bank set Balance=Balance+1000 where Id='0002'; set @error=@error+@@ERROR; if @error>0 begin rollback transaction end else begin commit transaction end
使用try-catch)(减少代码量)
begin transaction begin try update bank set Balance=Balance-1000 where Id='0001'; update bank set Balance=Balance+1000 where Id='0002'; commit transaction end try begin catch rollback transaction end catch
2存储过程(转账)
alter proc usp_MoveBalance @cash money, @inBankId char(4), @OutBankId char(4), @currentCash money output, --显示余额 @flag bit output --是否转成功 as begin begin transaction begin try update bank set Balance=Balance-@cash where Id=@OutBankId; update bank set Balance=Balance+@cash where Id=@InBankId; set @flag=1; commit transaction end try begin catch set @flag=0; rollback transaction end catch select @currentCash=Balance from bank where Id=@OutBankId; end --执行存储过程 declare @flag bit; declare @currentCash money; exec usp_MoveBalance 100,'0002','0001',@currentCash output,@flag output select @flag select @currentCash
3.触发器-(如果给任何账户打钱,都会把钱打到'0004'这个账号)(instead of)还有另一种触发器after(写for默认是after)
create trigger TriBankUpdate on bank instead of Update as begin declare @afterUpdateCash money; declare @beforeUpdateCash money; declare @cash money; select @afterUpdateCash=Balance from inserted; select @beforeUpdateCash=Balance from deleted; set @cash=@afterUpdateCash-@beforeUpdateCash; if @cash>0 begin Update bank set Balance=Balance+@cash where Id='0004'; end end -------------------------------------- --测试 select * from bank update bank set Balance=Balance+1000 where Id='0001';
相关文章推荐
- oracle 触发器和存储过程简单例子
- msyql中关于触发器储存过程定时任务的简单例子
- 数据库中的事务、存储过程和触发器的简单使用
- 简单说说MYSQL的触发器(例子包括了存储过程)
- MySQL事务、存储过程、视图、自定义函数、触发器、事件的简单使用及理解
- 数据库封装类DataOperation改进(支持事务、存储过程、简单使用例子)
- MySQL 触发器、存储过程、事务简单示例
- mysql视图,存储过程,游标,触发器,事务简单了解
- 存储过程、函数、带事务的触发器——对比
- TensorFlow笔记——关于MNIST数据的一个简单的例子
- 简单统计报表例子(存储过程)
- 关于自治事务解决触发器导致"ORA-04091:触发器/函数不能读它"不可行的验证
- 关于在vp下dof模型驱动的简单例子
- 触发器中调用存储过程,事务的使用
- 关于ExpandableListView用法的一个简单小例子
- 关于 OnMouseWheelDown、OnMouseWheelUp 等事件的简单例子 - 回复 "巅枫" 的问题
- 关于Python的web模板jinja2的简单例子
- MYSQL--存储过程-触发器-事务
- 关于ExpandableListView用法的一个简单小例子
- MySql最简单的触发器例子