如何在SQLServer中使用级联删除?我有两个表:T1和T2,它们是现有的有数据的表。T1和T2之间有一对多的关系。如何在SQLServer中更改表定义以执行级联删除,当从T1删除记录时,T2中的所有关联记录也被删除。他们之间存在着外来的限制。我不想删除表或创建一个触发器来执行T2的删除。例如,当我删除一个员工时,所有的考核记录也应该会消失。T1-雇员,Employee ID
Name
StatusT2-业绩审查,Employee ID - 2009 Review
Employee ID - 2010 Review
3 回答
RISEBY
TA贡献1856条经验 获得超5个赞
删除现有的外键约束, 添加一个新的 ON DELETE CASCADE
设置已启用。
ALTER TABLE dbo.T2 DROP CONSTRAINT FK_T1_T2 -- or whatever it's calledALTER TABLE dbo.T2 ADD CONSTRAINT FK_T1_T2_Cascade FOREIGN KEY (EmployeeID) REFERENCES dbo.T1(EmployeeID) ON DELETE CASCADE
江户川乱折腾
TA贡献1851条经验 获得超5个赞
ON DELETE CASCADE
ADD CONSTRAINT
SELECT OBJECT_NAME(f.parent_object_id) AS 'Table name', COL_NAME(fc.parent_object_id,fc.parent_column_id) AS 'Field name', delete_referential_action_desc AS 'On Delete'FROM sys.foreign_keys AS f, sys.foreign_key_columns AS fc, sys.tables t WHERE f.OBJECT_ID = fc.constraint_object_idAND t.OBJECT_ID = fc.referenced_object_idORDER BY 1
DROP
sp_help 'TableName'
添加回答
举报
0/150
提交
取消