--使用SQL-SERVER自带的数据库作范例
create trigger trtitles_upd on titles
for update
as
declare @mnyoldprice money,
@mnynewprice money,
@chvtitleid varchar(6),
@chvmsg varchar(255),
@inttotalqty integer
if update(price)
begin
declare cupricechange cursor
for
select d.title_id, d.price, i.price
from inserted i inner join deleted d
on i.title_id = d.title_id
open cupricechange
fetch next from cupricechange into
@ c h v titleid, @mnyoldprice, @mnynewprice
while (@@fetch_status <> -1)
begin
select @inttotalqty = sum(qty)
from sales
where title_id = @chvtitleid
if @mnynewprice > @mnyoldprice * 1.25 and @inttotalqty < 100
begin
select @chvmsg = 'an attempt has been made to reduce'
+ ' the price of title'
+ ' ' + @chvtitleid + ' by more than 25% from'
+ ' ' + convert ( varchar(10), @mnyoldprice) + ' to'
+ ' ' + convert ( varchar(10), @mnynewprice) + '.'
+ ' this is transaction has been rolled back.'
print @chvmsg
print ' '
update titles
set price = @mnyoldprice
where title_id = @chvtitleid
end
fetch next from cupricechange
into @chvtitleid, @mnyoldprice, @mnynewprice
end
deallocate cupricechange
end
go
--将print换成insert语句
--IN BANK AND BROKERAGE
--使用SQL-SERVER自带的数据库作范例
CREATE TRIGGER trAuthors_InsUpd ON Authors
FOR UPDATE
AS
DECLARE @intRowCount int
SELECT @intRowCount = @@RowCount
IF @intRowCount > 0
BEGIN
IF (NOT EXISTS
(
SELECT account FROM bank WHERE account IN
(SELECT account FROM inserted)
UNION
SELECT account FROM brokerage WHERE account IN
(SELECT account FROM inserted)
)
)
BEGIN
RAISERROR(56000, 10, 1)
ROLLBACK TRANSACTION
RETURN
END
END
CREATE trigger Chargeinfo_Update on StuChargeInfo
for update
as
begin tran
begin
if update(ChargePNum)
update SchBasicInfo set SchBasicInfo.CPNum=SchBasicInfo.CPNum+i.ChargePNum-j.ChargePNum from inserted i,deleted j where left(i.CodeID,13)=SchBasicInfo.SchCode and left(j.CodeID,13)=SchBasicInfo.SchCode
update SchGCCount set SchGCCount.CPNum=SchGCCount.CPNum+i.ChargePNum-j.ChargePNum from inserted i,deleted j where left(i.CodeID,13)=SchGCCount.SchCode and left(j.CodeID,13)=SchGCCount.SchCode and substring(j.CodeID,14,4)=SchGCCount.Grade and substring(i.CodeID,14,4)=SchGCCount.Grade and substring(i.CodeID,20,2)=SchGCCount.ClassID and substring(j.CodeID,20,2)=SchGCCount.ClassID
end
if @@error=0
begin
commit tran
end
else
begin
rollback tran
raiserror('更新数据失败,错误号为d%',12,1,@@error)
end