How do I use cascade delete with SQL Server?

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

    To add "Cascade delete" to an existing foreign key in SQL Server Management Studio:

    First, select your Foreign Key, and open it's "DROP and Create To.." in a new Query window.

    Then, just add ON DELETE CASCADE to the ADD CONSTRAINT command:

    And hit the "Execute" button to run this query.

    By the way, to get a list of your Foreign Keys, and see which ones have "Cascade delete" turned on, you can run this script:

    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_id
    AND t.OBJECT_ID = fc.referenced_object_id
    ORDER BY 1
    

    And if you ever find that you can't DROP a particular table due to a Foreign Key constraint, but you can't work out which FK is causing the problem, then you can run this command:

    sp_help 'TableName'
    

    The SQL in that article lists all FKs which reference a particular table.

    Hope all this helps.

    Apologies for the long finger. I was just trying to make a point.

提交回复
热议问题