0

我在 sql server 2008 R2 中有一个数据库,它有很多表(超过 200 个)并且表之间有很多关系。 大多数关系中的删除规则是无操作 我需要一次将所有关系删除规则更新为级联由于我的数据库中的关系太多我不想一个一个地这样做有什么办法吗?

4

1 回答 1

1

通常,当您使用 SSMS GUI 更改外键约束时,后台的 SQL Server 实际上会删除并重新创建相同的约束。

这是一个脚本,它将生成用于删除所有 FKey 并使用ON UPDATE CASCADE ON DELETE CASCADE选项重新创建它们的 SQL

假设是,您所有的 FKey 都名为“FK .....”

SET NOCOUNT ON;

DECLARE @Objects TABLE
(
ID int identity(1,1),
TableName sysname,
SchemaName sysname
)

INSERT INTO @Objects (TableName, SchemaName)
    SELECT
        TABLE_NAME,
        CONSTRAINT_SCHEMA
    FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
    WHERE CONSTRAINT_NAME LIKE 'FK%' 

DECLARE @min int, @max int,@table sysname,@schema sysname

SELECT @min = 1, @max = MAX(ID) FROM @Objects

WHILE @min <=@max
BEGIN

SELECT
    @table = TableName,@schema = SchemaName FROM @Objects WHERE ID = @min

print '/*Drop Foreign Key Statements for [' + @schema + '].[' + @table + ']*/'
SELECT
    'ALTER TABLE [' + SCHEMA_NAME(o.schema_id) + '].[' + o.name + '] 
DROP CONSTRAINT [' + fk.name + ']'
    FROM sys.foreign_keys fk
    INNER JOIN sys.objects o
        ON fk.parent_object_id = o.object_id
    WHERE o.name = @table AND
    SCHEMA_NAME(o.schema_id) = @schema

    print '/*Create Foreign Key Statements for [' 
+ @schema + '].[' + @table + ']*/'
    SELECT
        'ALTER TABLE [' + SCHEMA_NAME(o.schema_id) + '].[' + o.name + '] 
ADD CONSTRAINT [' + fk.name + '] FOREIGN KEY ([' + c.name + ']) 
    REFERENCES [' + SCHEMA_NAME(refob.schema_id) + '].[' + refob.name + ']
([' + refcol.name + '])ON UPDATE  CASCADE ON DELETE  CASCADE'
    FROM sys.foreign_key_columns fkc
    INNER JOIN sys.foreign_keys fk
        ON fkc.constraint_object_id = fk.object_id
    INNER JOIN sys.objects o
        ON fk.parent_object_id = o.object_id
    INNER JOIN sys.columns c
        ON fkc.parent_column_id = c.column_id AND
    o.object_id = c.object_id
INNER JOIN sys.objects refob
    ON fkc.referenced_object_id = refob.object_id
INNER JOIN sys.columns refcol
    ON fkc.referenced_column_id = refcol.column_id AND
    fkc.referenced_object_id = refcol.object_id
WHERE o.name = @table AND
SCHEMA_NAME(o.schema_id) = @schema

SET @min = @min+1
END

希望这可以帮助。

拉吉

PS:将查询输出设置为文本会有所帮助。另请阅读针对您的问题发表的评论。随意设置CASCADE未必是正确的做法

于 2013-05-20T11:47:29.537 回答