SQL SERVER 7触发器(二)

2014-11-24 13:24:01 · 作者: · 浏览: 3
,我们需要修改当前电脑的使用状态为0(正常状态),当一台电脑正在使用时,我们需要修改当前电脑的使用状态为1(使用状态);当修改记录表时,要获取电脑的信息。
为记录表创建update触发器,这样就可以同时修改电脑的状态信息。
-------关键代码------
create trigger tr_update_recordInfo
on recordInfo
for update
as
declare @beforePCId int
declare @afterPCId int
select @beforePCId =PCId from deleted
select @afterPCId=PCID from inserted
---根据电脑编号修改使用状态-----
---根据以前使用的电脑编号把电脑的使用状态改为:
update PCInfo set PCUse=0 where PCId=@beforePCId
---根据现在使用的电脑编号把电脑的使用状态改为:
update PCInfo set PCUse=1 where PCId=@afterPCId
----显示电脑换机成功
print'换机成功!从'+convert(varchar(10),@beforePCId)+'号电脑换到'+convert(varchar(10),@afterPCId)+'号电脑'
go
/*测试update触发器,修改电脑编号*/
--显示更改前,记录表中的数据
print'更改前,记录表中的数据'
select * from recordInfo
--显示更改前,电脑表中的数据
print'更改前,电脑表中的数据'
select * from PCInfo
set nocount on
---把电脑号为1的改为2
update recordInfo set PCId=2 where PCId=1
---查看结果
print'更改后,记录表中的数据'
select * from recordInfo
print'更改后,电脑表中的数据'
select * from PCInfo
列级 UPDATE 触发器
update触发器无论是对表中的一行或多行,还是一列或多列,都将执行触发器操作。但是在实际需求中,可能只关心对特定列是否被更新。如果特定的列被更新,就执行触发器操作。这可以通过列上的update语法:if update<列名>来实现。在同一个触发器的定义语句中,可以使用多条if update 语句来对不同的列的修改执行不同的触发器操作。
例如,在网吧计费系统中上机时间一般由系统自动产生,默认为当前时间。为了防止非法人员有机可乘(作弊等),一般禁止修改。如何防止用户误操作而修改了上机时间,我们可以使用update(列名)函数来检测是否修改了某列。T-SQL 代码如下:
-------关键代码------
---创建update触发器,在上网记录表recordInfo上创建修改(列)触发器
create trigger tr_updateColum_recordInfo
on recordInfo
for update
as
---检查是否修改了上机时间(beginTime)
if update(beginTime)
begin
print'修改失败!'
raiserror('安全警告:上机时间不能修改,由系统自动产生',16,1)
rollback transaction ----回滚操作,撤销操作
end
go
-------关键代码------
set nocount on
---把上机时间修改为-5
update recordInfo set beginTime='2010-6-5'
5、instead of触发器的使用
instead of触发器的使用范围,instead of 触发器可以同时在数据表和视图中使用。通常在以下几种情况下,建议使用instead of触发器:
数据库里的数据禁止修改:例如电信部门的通话记录是不能修改的,一旦修改,则通话费用的计数将不准确。
有可能要回滚修改的SQL语句
在视图中使用触发器
用自己的方式去修改数据
instead of触发器的使用
例如,在网吧计费 系统中当用户的余额大于2元时才能上机,否则给出提示信息。在recordInfo表上创建instead of触发器,向recordInfo表插入上机信息时执行触发操作。
---创建update触发器,在上网记录表recordInfo上创建修改(列)触发器
create trigger tr_updateColum1_recordInfo
on recordInfo
instead of insert
as
declare @cardbalance int --声明用于存储用户余额的变量
declare @CardId int --声明用于存储用户卡的编号的变量
declare @PCId int --声明用于存储电脑编号的变量
---inserted临时表中获取插入的记录行信息,包括电脑编号、卡的编号
select @cardId=cardId,@PCId=PCId from inserted
select @cardbalance=cardBalance from cardInfo where CardId=@CardId
print'您的余额为:'+convert(varchar(10),@cardBalance) ---打印余额信息
if(@cardBalance<2) ---判断余额多少,看能否正常上机
print'余额小于元,不能上机。请尽快充值!'
else
----根据电脑的编号修改电脑的使用状态更改为正在使用
update PCInfo set PCUse=1 where PCId=@PCId
----向recordInfo表插入上机记录
insert into recordInfo(cardId,PCId,beginTime)values(@CardId,@PCId,getdate())
print'上机成功'
-------关键代码------
set nocount on
declare @cardId int ---声明一个存储卡的编号的变量