SQL Script to alter ALL Foreign Keys to add ON DELETE CASCADE

后端 未结 7 1820
轻奢々
轻奢々 2020-12-04 08:21

I have a SQL 2005 database with approx 250 tables.

I want to temporarily enable ON DELETE CASCADE to all of the Foreign Keys so that I can do a bulk delete easily.

7条回答
  •  醉话见心
    2020-12-04 09:18

    make a new stored procedure, where the only parameter is the name of the table to process. In that procedure, you'll need to loop over sys.foreign_keys and sys.foreign_key_columns to build the proper drop and create syntax, just use a cursor and some prints (KISS).

    call this procedure with the syntax:

    EXEC sp_msforeachtable 'YourProcedureName ''?'''
    

    and it will run for each table. Take and run the output, and you are done.

提交回复
热议问题