sql server 触发器 trigger

做增删改操作时自动触发另一个操作。

触发器分类

  1. instead of 触发器:在执行操作之前被执行。
  2. after触发器:在执行操作之后被执行。

举例:

部门表 Department:

DepartmentId DepartmentName
001 总经办
002 市场部
003 人事部
004 财务部
005 软件部

员工表 People:

PeopleId DepartmentId PeopleName PeopleSex PeoplePhone
1 001 刘备 13558785478
2 001 刘备 13558785478
3 002 刘备 13558785478

1、假设有部门表和员工表,在添加员工的时候,该员工部门编号在部门表中找不到,则自动添加部门信息,部门名称为“新部门”。

create trigger tri_InsertPeople on People after insert
as
    if not exists(select * from Department where DepartmentId = (select DepartmentId from inserted) )
        begin
            insert into Department(DepartmentId,DepartmentName) values ((select DepartmentId from inserted), '新部门')
        end
go
  • tri_InsertPeople :触发器名
  • after insert:在插入之后触发
  • inserted:临时表的名字

2、删除一个部门的时候,将部门下的所有员工删除

create trigger tri_DeleteDept on Department after delete
as
    delete from People where DepartmentId = (select DepartmentId from deleted)
go

3、删除一个部门的时候,判断该部门下是否有员工,有则不删除,没有则删除。

create trigger tri_DeleteDept on Department instead of delete
as
    if not exists(select * from People where DepartmentId = (select DepartmentId from deleted) )
        delete from Department where DepartmentId = (select DepartmentId from deleted)
go

4、修改一个部门编号后,将该部门下所有员工的部门编号同步修改。

create trigger tri_UpdateDept on Department after update
as
    update People set DepartmentId = (select DepartmentId from inserted)
    where DepartmentId = (select DepartmentId from deleted)
go

你可能感兴趣的:(sql server 触发器 trigger)