SQLServer 2000与Oracle 8i相比较,在级联删除上有太多的限制
- 表内自关联不支持级联删除和级联更新
- 一个表内在有多个列同时关联于另一个表时,不支持多个级联删除
- 还有什么循环级联删除限制,等等
- .......
一大堆限制,如果要迁移Oracle到SqlServer麻烦多多,特别对于用于构造树型结构的表内自关联(比如部门表)的级联删除特别讨厌
考虑来考虑去,对于SqlServer不能支持的诸多级联删除只有采用最原始的方法,彻底不用外键关联,而是用触发器来解决
以下是经过验证的触发器实现范例(自关联例子)
放弃外键关联后所有的完整性检查都要通过触发器实现
--DELETE 级联删除,先删除,再删除所有级联的记录,采用递归触发器,当然要求数据库支持递归触发器功能开启(数据库属性设置中开启他),不过SqlServer只支持32级的递归啊
IF EXISTS (SELECT NAME FROM SYSOBJECTS
WHERE NAME = 'DEL_DOCUMENTTYPE_001' AND TYPE = 'TR')
DROP TRIGGER DEL_DOCUMENTTYPE_001
GO
CREATE TRIGGER DEL_DOCUMENTTYPE_001
ON dbo.DOCUMENTTYPE
FOR DELETE
AS
IF (SELECT COUNT(*) FROM DELETED) > 0
DELETE FROM dbo.DOCUMENTTYPE WHERE UPNO IN (SELECT NO FROM DELETED)
GO
--INSERT 数据插入,验证外键关联逻辑,错误抛出出错信息
IF EXISTS (SELECT NAME FROM SYSOBJECTS
WHERE NAME = 'INS_DOCUMENTTYPE_001' AND TYPE = 'TR')
DROP TRIGGER INS_DOCUMENTTYPE_001
GO
CREATE TRIGGER INS_DOCUMENTTYPE_001
ON dbo.DOCUMENTTYPE
FOR INSERT
AS
IF (SELECT COUNT(*) FROM INSERTED WHERE UPNO IS NOT NULL
AND (UPNO = NO OR UPNO NOT IN (SELECT NO FROM dbo.DOCUMENTTYPE))) > 0
BEGIN
DELETE FROM dbo.DOCUMENTTYPE WHERE NO IN (SELECT NO FROM INSERTED)
RAISERROR('在被引用表 dbo.DOCUMENTTYPE 中没有与外键 UPNO 的引用列的列表匹配的主键或候选键。',16,1)
END
GO
--UPDATE 数据更新,如果更新了外键,验证外键存在
IF EXISTS (SELECT NAME FROM SYSOBJECTS
WHERE NAME = 'UPD_DOCUMENTTYPE_001' AND TYPE = 'TR')
DROP TRIGGER UPD_DOCUMENTTYPE_001
GO
CREATE TRIGGER UPD_DOCUMENTTYPE_001
ON dbo.DOCUMENTTYPE
FOR UPDATE
AS
IF (SELECT COUNT(*) FROM INSERTED WHERE UPNO IS NOT NULL
AND (UPNO = NO OR UPNO NOT IN (SELECT NO FROM dbo.DOCUMENTTYPE))) > 0
BEGIN
SET IDENTITY_INSERT dbo.DOCUMENTTYPE ON
DELETE FROM dbo.DOCUMENTTYPE WHERE NO IN (SELECT NO FROM INSERTED)
-- INSERT INTO dbo.DOCUMENTTYPE SELECT * FROM INSERTED
SELECT * INTO dbo.DOCUMENTTYPE FROM INSERTED
SET IDENTITY_INSERT dbo.DOCUMENTTYPE OFF
RAISERROR('在被引用表 dbo.DOCUMENTTYPE 中没有与外键 UPNO 的引用列的列表匹配的主键或候选键。',16,1)
END
GO
简单修改基本上可以解决所有SqlServer数据库级联删除和级联更新的问题
|
来源:https://www.cnblogs.com/wuliang/archive/2007/11/27/974194.html