How do I use cascade delete with SQL Server?

后端 未结 8 1251
抹茶落季
抹茶落季 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条回答
  •  猫巷女王i
    2020-11-22 01:43

    First To Enable ONCascade property:

    1.Drop the existing foreign key constraint

    2.add a new one with the ON DELETE CASCADE setting enabled

    Ex:

    IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.Response'))
     BEGIN 
    
    ALTER TABLE [dbo].[Response] DROP CONSTRAINT [FK_Response_Request]  
    
    ALTER TABLE [dbo].[Response] WITH CHECK ADD CONSTRAINT [FK_Response_Request]  FOREIGN KEY([RequestId])
    REFERENCES [dbo].[Request] ([RequestId])
    ON DELETE CASCADE
    END
    
    ELSE
    
     BEGIN 
     ALTER TABLE [dbo].[Response] WITH CHECK ADD CONSTRAINT [FK_Response_Request]  FOREIGN KEY([RequestId])
    REFERENCES [dbo].[Request] ([RequestId])
    ON DELETE CASCADE
    END
    

    Second To Disable ONCascade property:

    1.Drop the existing foreign key constraint

    2.Add a new one with the ON DELETE NO ACTION setting enabled

    Ex:

    IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.Response'))
     BEGIN 
    ALTER TABLE [dbo].[Response] DROP CONSTRAINT [FK_Response_Request]  
    
    ALTER TABLE [dbo].[Response] WITH CHECK ADD CONSTRAINT [FK_Response_Request]  FOREIGN KEY([RequestId])
    REFERENCES [dbo].[Request] ([RequestId])
    ON DELETE CASCADE
    END
    
    ELSE
    
     BEGIN 
     ALTER TABLE [dbo].[Response] WITH CHECK ADD CONSTRAINT [FK_Response_Request]  FOREIGN KEY([RequestId])
    REFERENCES [dbo].[Request] ([RequestId])
    ON DELETE NO ACTION 
    END
    

提交回复
热议问题