SQL Server数据迁移失败

时间:2014-08-15 17:46:39

标签: sql sql-server-2008

因此我们将SQL服务器迁移到了新平台。在此移动过程中,主键和外键未被传输。

有没有办法可以从旧表中编写密钥并将它们添加到新表中?

看起来他们不会重做它,只是手动给我们所有的钥匙。任何快速/安全的方式都是值得赞赏的。

SQL Server 2008

2 个答案:

答案 0 :(得分:1)

是的,你会爱上这个。我必须偶尔删除并重新添加FK(就像我想要更改SQL为FK强制执行而被劫持的索引时),所以我编写了一个视图,它将为我提供drop和add语句: / p>
select *, addqry = 'ALTER TABLE '+FKtable+' WITH ' + case when is_not_trusted = 1 then 'NO' else '' end + 'CHECK'
                    + ' ADD  CONSTRAINT ['+FK+'] FOREIGN KEY ('+FKcol+') '
                    + ' REFERENCES '+PKtable+' ('+PKcol+')'+' ON UPDATE '+onUpdate+' ON DELETE '+onDelete
                    + case when is_not_for_replication = 1 then ' NOT FOR REPLICATION' else '' end + ';'
                    + case when is_disabled = 1 then '  ALTER TABLE '+FKtable+' NOCHECK CONSTRAINT ['+FK+'];' else '' end
    ,dropqry = 'ALTER TABLE '+FKtable+' DROP ['+FK+'];'
from (
    select   PKtable        = object_schema_name(f.referenced_object_id)+'.'+object_name(f.referenced_object_id)
        ,PKtbl      = object_name(f.referenced_object_id)
        ,PKcol      = pc.name
        ,FKtable        = object_schema_name(f.parent_object_id)+'.'+object_name(f.parent_object_id)
        ,FKtbl      = object_name(f.parent_object_id)
        ,colseq     = fk.constraint_column_id
        ,FKcol      = fc.name
        ,FK     = object_name(f.object_id)
        ,onUpdate   = replace(f.update_referential_action_desc collate SQL_Latin1_General_CP1_CI_AS, '_', ' ')
        ,onDelete   = replace(f.delete_referential_action_desc collate SQL_Latin1_General_CP1_CI_AS, '_', ' ')
        ,f.is_disabled
        ,f.is_not_trusted
        ,f.is_not_for_replication
    from sys.foreign_key_columns as fk
        join sys.foreign_keys f on fk.constraint_object_id = f.object_id
        join sys.columns as fc on f.parent_object_id = fc.object_id and fk.parent_column_id = fc.column_id
        join sys.columns as pc on f.referenced_object_id = pc.object_id and fk.referenced_column_id = pc.column_id
) t

答案 1 :(得分:1)

由于您正在处理主键和外键,我会使用SQL Server数据库工具(SSDT)之类的(免费)工具。这是一个与Visual Studio集成的Microsoft工具(如果有的话 - 您不需要它)。它将使目标模式与源模式同步。它基本上像Red Gat Schema Compare这样的工具,除了它是免费的。而且效果很好。使用这样的工具将确保您的整个架构被移动,而不仅仅是PK和FK。