How do I use cascade delete with SQL Server?

后端 未结 8 1255
抹茶落季
抹茶落季 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
    

提交回复
热议问题