有这样的应用情形,除了使用2表之间主外键约束中启用级联修改和级联删除这种SQL Server自带的解决方案外,我们还可以使用触发器来完成类似的功能,以下通过一个删除来举例说明:
假如一个SysFuncDic(功能字典表)、SysFuncRights(功能权限表),功能权限表中的FuncID和功能字典表中FuncID有外键约束关系,现在我们要删除SysFuncDic中的记录,因为做过外键约束关系,所以无法删除。解决的办法是首先删除SysFuncRights表中所有与FuncID对应的记录即可。
create table SysFuncDic ( FuncID int not null identity(1,1) primary key, FuncName varchar(100) ) create table SysFuncRights ( ID int not null primary key identity(1,1), FuncID int not null, EmpID int not null ) insert into SysFuncDic values('AA') insert into SysFuncDic values('BB') insert into SysFuncDic values('CC') insert into SysFuncRights values(1,12) insert into SysFuncRights values(2,12) insert into SysFuncRights values(3,12) /***********************删除触发器**************************/ create trigger tri_delete on SysFuncDic instead of delete as begin declare @FuncID int; select @FuncID = FuncID from deleted; delete SysFuncDic where FuncID = @FuncID; delete SysFuncRights where FuncID = @FuncID; end /**********************************************************/ select * from SysFuncDic; --查询功能字典表记录 select * from SysFuncRights; --查询功能权限表中记录 delete from SysFuncDic where FuncID=1; --删除功能字典表中记录,进行测试