SQL Server 2005外键级联

时间:2013-02-28 04:00:04

标签: sql-server-2005

我有一个表ParentTableid, Name, town)及其子表humanmother, father),其中两列都包含父表的映射。

父表的列town包含带有Towntownid, townname)的外键引用,并且该城镇添加了外键引用。

现在的问题是我需要为人类表提供级联约束,但在SQL Server中,同一个父表的多列不能给出级联。所以我创建了这样的触发器,

create trigger DEL_Parent                                             
ON Parent  
instead of delete as      
   set nocount on       

   delete from human       
   where mother IN (select id from deleted)        
      or father IN (select id from deleted)

 delete from Parent where id in(select id from deleted). 

但是当我尝试执行触发器时,系统会显示以下错误

  

无法创建而不是删除或代替更新触发器   父表上的DEL_Parent。这是因为桌子有外国人   带有级联删除或更新的密钥。

如何解决问题?提前谢谢。

2 个答案:

答案 0 :(得分:2)

将查询修改为:

create trigger DEL_Parent                                             
ON Parent  
after delete as      
  set nocount on       

  delete 
  from human       
  where mother IN (select id from deleted)        
     or father IN (select id from deleted)

  delete 
  from Parent 
  where id in(select id from deleted)

因为无法在具有使用INSTEAD OF DELETE操作定义的外键的表上定义DELETE触发器。

答案 1 :(得分:0)

无法在具有使用DELETE操作定义的外键的表上定义INSTEAD OF DELETE触发器。

来源:http://msdn.microsoft.com/en-us/library/ms191208(v=sql.90).aspx

所以,我想如果你想要,你必须放弃你的cascade delete并用触发器处理它,如果你还想强制执行它。