SQL脚本更改所有外键以添加ON DELETE CASCADE

我有一个SQL 2005数据库约250表。

我想临时启用ON DELETE CASCADE到所有外键,使我可以轻松地批量删除。

然后我想关闭所有外键上的DELETE CASCADE。

我知道这样做的唯一方法是使用Management Studio生成一个完整的数据库创建脚本,做某种搜索和替换除去外键,除了外键,保存脚本,然后做一些更多的搜索和替换添加ON DELETE CASCADE。

然后我运行脚本,做我的删除,然后运行其他脚本。

有更容易的方法来生成这个脚本吗?这种方法似乎太容易出错,我将不得不保持脚本更新我们对数据库所做的任何其他更改,或手动重新生成每次我可能需要使用它。

是一个替代选项,在系统表上运行select来为我生成脚本吗?甚至可以在启用和禁用ON DELETE CASCADE的系统表上运行更新?

这里是我用于类似目的的脚本。它不支持复合外键(它使用多个字段。)它可能需要一些调整,它将适合您的情况。编辑:特别是它不能正确处理多列外键。

select
  DropStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema + 
      '].[' + ForeignKeys.ForeignTableName + 
      '] DROP CONSTRAINT [' + ForeignKeys.ForeignKeyName + ']; '
,  CreateStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema + 
      '].[' + ForeignKeys.ForeignTableName + 
      '] WITH CHECK ADD CONSTRAINT [' +  ForeignKeys.ForeignKeyName + 
      '] FOREIGN KEY([' + ForeignKeys.ForeignTableColumn + 
      ']) REFERENCES [' + schema_name(sys.objects.schema_id) + '].[' +
  sys.objects.[name] + ']([' +
  sys.columns.[name] + ']) ON DELETE CASCADE; '
 from sys.objects
  inner join sys.columns
    on (sys.columns.[object_id] = sys.objects.[object_id])
  inner join (
    select sys.foreign_keys.[name] as ForeignKeyName
     ,schema_name(sys.objects.schema_id) as ForeignTableSchema
     ,sys.objects.[name] as ForeignTableName
     ,sys.columns.[name]  as ForeignTableColumn
     ,sys.foreign_keys.referenced_object_id as referenced_object_id
     ,sys.foreign_key_columns.referenced_column_id as referenced_column_id
     from sys.foreign_keys
      inner join sys.foreign_key_columns
        on (sys.foreign_key_columns.constraint_object_id
          = sys.foreign_keys.[object_id])
      inner join sys.objects
        on (sys.objects.[object_id]
          = sys.foreign_keys.parent_object_id)
        inner join sys.columns
          on (sys.columns.[object_id]
            = sys.objects.[object_id])
           and (sys.columns.column_id
            = sys.foreign_key_columns.parent_column_id)
    ) ForeignKeys
    on (ForeignKeys.referenced_object_id = sys.objects.[object_id])
     and (ForeignKeys.referenced_column_id = sys.columns.column_id)
 where (sys.objects.[type] = 'U')
  and (sys.objects.[name] not in ('sysdiagrams'))
http://stackoverflow.com/questions/868620/sql-script-to-alter-all-foreign-keys-to-add-on-delete-cascade

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:SQL脚本更改所有外键以添加ON DELETE CASCADE