我需要一个基本的sql触发器的例子,现在我解释一下:
我有一个包含5列的表(column1,power,column3,column4,times)
“权力”的值实时变化(是数字),他的数据类型是“真实的” 而“times”的数据类型是'int'
我会触发每次“力量”增加0倍'1次
抱歉,如果我的英语不完美!并希望你理解我的意思!如果有什么不明确告诉我,我会尽力解释! :)
答案 0 :(得分:4)
可能的基本触发器:
create trigger MyBasicTrigger on MyBasicTable
after insert, update
as
-- Trigger rowcount should not mess with update that triggered it, search for it in documentation provided here
set NoCount ON
-- If power is mentioned in update/insert statement at all
if update(Power)
begin
-- Update times for each changed row that has value of power 0
-- Inserted table holds new values in updated rows
-- You didn't mention your PK column(s), so I assume the name would be "ID"
update MyBasicTable set Times = Times + 1
from MyBasicTable inner join inserted on MyBasicTable.ID = inserted.ID
where Inserted.Power = 0
end
NoCount和更新(电源)的文档是here。
答案 1 :(得分:2)
假设column1是主键,触发器的一般形式如下:
create trigger MyPower
on MyTable
after insert, update
as
if exists (select column1
from inserted i join MyTable m
on i.column1 = m.column1
and i.power = 0)
update MyTable set times = times + 1
where exists (select column1 from inserted i
join MyTable m
on i.column1 = m.column1)