How do I use cascade delete with SQL Server?

后端 未结 8 1128
抹茶落季
抹茶落季 2020-11-22 01:12

I have 2 tables: T1 and T2, they are existing tables with data. We have a one to many relationship between T1 and T2. How do I alter the table definitions to perform casca

相关标签:
8条回答
  • 2020-11-22 01:55

    You will need to,

    • Drop the existing foreign key constraint,
    • Add a new one with the ON DELETE CASCADE setting enabled.

    Something like:

    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
    
    0 讨论(0)
  • 2020-11-22 01:55

    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.

    0 讨论(0)
提交回复
热议问题