再来一个用触发器满足参照完整性约束的案例,一个员工表,一个工资表,两张表为一对多强耦合关系,员工离职需要删除员工信息,同时将工资信息也同步删除!
CREATE TABLE EMPLOYEES
(
ENO INT,
ENAME VARCHAR(20),
ESEX CHAR(2)
)
CREATE TABLE EMPLOYEES_Salary
(
esid int identity,
ENO INT,
esmoney money,
esTime datetime
)
SELECT * FROM EMPLOYEES AS EM
INNER JOIN EMPLOYEES_Salary AS ES ON EM.ENO = ES.ENO
在员工表上创建删除的触发器:
CREATE trigger EMPLOYEES_DELETE_Triger
on EMPLOYEES
for delete
AS
DECLARE @ENO int
--将保存在deleted临时表中的数据查询出来
SELECT @ENO = ENO FROM deleted
--同步删除子表数据
DELETE FROM EMPLOYEES_Salary WHERE ENO = @ENO
DELETE FROM EMPLOYEES WHERE ENO = 3