T-SQL 触发器

触发器

触发器是表进行插入(insert)、更新(update)或者删除(delet)的时候自动执行的特殊存储过程。

在SQL中触发器可以分为DML触发器和DDL触发器,其中会为响应多种数据定义语言(DDL)语句而触发,这些语句主要是 create,alter,drop 开头的语句。

DML触发器分为:

1、alter触发器

  • insert 触发器
  • update 触发器
  • delete 触发器

2、instead of 触发器(替代)

instead of  触发器可以用于监测视图

创建触发器的 语法:

create trigger 触发器名称
on 要监测的表名称
【with encryption】加密
for 要监测的动作 【insert,upda,delete】
as
T-SQL 语句
go

替代触发器:

例:

if exists (select * from sys.triggers where name='insteadof')
drop trigger insteadof
go
create trigger insteadof
on stuinfo
instead of delete
as
    declare @id int
    select @id = stuid from deleted
    delete from stumarks where stuid=@id
    delete from stuinfo where stuid=@id
go

delete from StuInfo where stuid=1
select * from StuInfo

监测视图:

if exists (select * from sys.views where name='v_del')
drop view v_del
go
create view v_del(定义视图)
as
    select StuInfo.stuid,stuname,stusex,subject,score
    from StuInfo,StuMarks
    where StuInfo.stuid=StuMarks.stuid
go


if exists (select * from sys.triggers where name='insteadf')
drop trigger insteadf
go
create trigger insteadf
on v_del(监测视图)
instead of delete
as
    declare @id int
    select @id = stuid from deleted
    delete from stumarks where stuid=@id
    delete from stuinfo where stuid=@id
go

delete from v_del where stuid=3
select * from v_del

你可能感兴趣的:(T-SQL)