我有2个表:T1和T2,它们是现有的数据表。T1和T2之间有一对多的关系。当删除T1中的记录时,如何修改表定义以在SQL Server中执行级联删除,T2中的所有关联记录也被删除。

外国的约束在他们之间存在。我不想删除表或创建触发器来删除T2。例如,当我删除一个员工时,所有的评审记录也应该消失了。

T1 -员工,

Employee ID      
Name
Status

T2 -工作表现检讨,

Employee ID - 2009 Review
Employee ID - 2010 Review

当前回答

If the one to many relationship is from T1 to T2 then it doesn't represent a function and therefore cannot be used to deduce or infer an inverse function that guarantees the resulting T2 value doesn't omit tuples of T1 join T2 that are deductively valid, because there is no deductively valid inverse function. ( representing functions was the purpose of primary keys. ) The answer in SQL think is yes you can do it. The answer in relational think is no you can't do it. See points of ambiguity in Codd 1970. The relationship would have to be many-to-one from T1 to T2.

其他回答

If the one to many relationship is from T1 to T2 then it doesn't represent a function and therefore cannot be used to deduce or infer an inverse function that guarantees the resulting T2 value doesn't omit tuples of T1 join T2 that are deductively valid, because there is no deductively valid inverse function. ( representing functions was the purpose of primary keys. ) The answer in SQL think is yes you can do it. The answer in relational think is no you can't do it. See points of ambiguity in Codd 1970. The relationship would have to be many-to-one from T1 to T2.

你需要,

删除现有的外键约束, 添加一个启用ON DELETE CASCADE设置的新对象。

喜欢的东西:

ALTER TABLE dbo.T2
   DROP CONSTRAINT FK_T1_T2   -- or whatever it's called

ALTER TABLE dbo.T2
   ADD CONSTRAINT FK_T1_T2_Cascade
   FOREIGN KEY (EmployeeID) REFERENCES dbo.T1(EmployeeID) ON DELETE CASCADE

我认为你不能只是删除表属性,如果这是实际的生产数据,只是删除不影响表模式的内容。

您可以使用SQL Server Management Studio完成此操作。

→右键单击表格设计,在左侧窗格中选择关系,在右侧窗格中选择外键,展开菜单“INSERT and UPDATE specification”,并选择“Cascade”作为删除规则。

使用像这样的东西

ALTER TABLE T2
ADD CONSTRAINT fk_employee
FOREIGN KEY (employeeID)
REFERENCES T1 (employeeID)
ON DELETE CASCADE;

填写正确的列名,就可以完成设置。正如mark_s正确地指出的那样,如果已经有一个外键约束,可能需要先删除旧的外键约束,然后再创建新的外键约束。