insert触发器:
create table stuinfo
(
num varchar(10),
name varchar(10)
)
create table classinfo
(
serialno varchar(10),
totalno int
)
classinfo表
stuinfo表
比如说班级编号位1001的人数1个
insert into classinfo values(‘1001‘,1)
下来创建触发器
create trigger info //触发器名字
on stuinfo // 该触发器是在那个表改变的时候发生
for insert //在那个事件发生
as
update classinfo set totalno=totalno+1
where serialno=(select num from inserted) //inserted为临时表
运行一下三条命令,验证结果
select totalno from classinfo where serialno=‘1001‘
insert into stuinfo values( ‘1001‘,‘xiaobai‘)
select totalno from classinfo where serialno=‘1001‘
前后对比
delete触发器:
create trigger del
on stuinfo
for delete
as
update classinfo set totalno=totalno-1
where serialno=(select num from deleted)
运行一下三条命令,验证结果
select totalno from classinfo where serialno=‘1001‘
delete from stuinfo where num=‘1001‘
select totalno from classinfo where serialno=‘1001‘
update触发器:
create trigger upd
on stuinfo
for update
as
if(update(name))
begin
print ‘name changed‘
end
else
print ‘not changed‘
运行一下三条命令,验证结果
select * from stuinfo where num=‘1001‘
update stuinfo set name=‘小白‘ where num=‘1001‘
select * from stuinfo where num=‘1001‘