浅谈SQL Server 数据库之触发器
2010-02-26 00:00:00 来源:WEB开发网触发器5_delete 触发器SQL
delete 触发器
/* 实现: 当清除'交易信息表'的数据时,
自动备份被清除的数据到backupTable表中
*/
------------------ delete 触发器 ------------------
use TriggerDatabase
go
if exists (select * from sysobjects
where name='trig_delete_transInfo')
drop trigger trig_delete_transInfo
go
create trigger trig_delete_transInfo
on transInfo after delete -- for | after
as
print '开始备份数据,请稍后......'
-- 如果数据库中,不存在 backupTable 表
if not exists(select * from sysobjects
where name='backupTable')
select * into backupTable from deleted --deleted临时表
else
insert into backupTable select * from deleted
print '备份成功,备份表 backupTable 中的数据为:'
select * from backupTable;
go
------------------ 测试触发器 ------------------
set nocount on
delete from transInfo; --测试
--查看结果
select * from transInfo
select * from backupTable
触发器6_update 触发器SQL
update 触发器
------------------ update 触发器 ------------------
use TriggerDatabase
go
if exists (select * from sysobjects
where name='trig_update_bank')
drop trigger trig_update_bank
go
create trigger trig_update_bank
on bank for update --在bank表上创建update触发器
as
declare @beforeMoney money,
@afterMoney money,
@currentTrans money --当前交易金额
--从deleted临时表,获取交易前的余额
select @beforeMoney = currentMoney from deleted;
--从inserted临时表,获取交易后的余额
select @afterMoney = currentMoney from inserted;
if abs(@afterMoney-@beforeMoney) > 2000
begin
print '当前交易金额为:' +
convert(varchar(20),abs(@afterMoney-@beforeMoney))
-- 自定义错误消息
raiserror('每次交易金额不能超过2000元,交易失败!',16,1)
rollback transaction --回滚事务,撤销交易!
/* 注意:
触发器是一个特殊的事务单元
不需显示声明begin transaction
*/
end
go
------------------ 测试触发器 ------------------
set nocount on
--测试1: 在 bank表触发 update触发器
update bank set currentMoney = currentMoney + 25000
where cardID = '1001 0001'
--测试2: 通过 transInfo表的 trig_insert_transInfo触发器
-- 间接触发 bank表的 trig_update_bank触发器
insert into transInfo(cardID,transType,transMoney)
values('1001 0001','存入',10000);
--查看结果
select * from bank
select * from transInfo
更多精彩
赞助商链接