如何将数据库图表从一个服务器移动到另一个服务器

9

我在测试数据库中创建了一个新的数据库图表,它位于sitde01服务器上。现在我想将它迁移到另一个服务器。如何将其迁移至另一个服务器。


一个图表只是所有主键和外键的视觉展示...你可以轻松地创建一个脚本来使用这些信息更新现有的数据库。 - balexandre
1
@balexandre - 一点也不正确。在图表中,您可以有文本注释。此外,图表中表格的图形布局可以传达表格如何逻辑分组。 - anon
3个回答

16

虽然这可以实现,但是非常麻烦。以下是过程的概述和一些脚本。

图表存储在名为sysDiagrams的“系统”表中。此表(仅?)在单击SSMS中的图表节点时创建,它会询问您是否要创建支持图表的对象,并单击“是”。在源数据库和目标数据库上都执行此操作。

在“源”数据库中创建一个或多个图表。

查看sysDiagrams的结构和内容。请注意,列diagram_id是标识列。每个图表都存储1行。(您不必关心,但在SQL 2000中,它曾经是4或5行。)

要将其复制到同一SQL实例上的另一个数据库中,最简单的方法是在表之间执行INSERT... SELECT...语句。由于标识列的存在,您必须使用SET IDENTITY_INSERT并可能在目标计算机上分配新的标识值。这很烦人,但并不是特别困难。

以下脚本将从一个数据库复制所有图表到同一服务器上的另一个数据库中(这是我归档那些花费了很长时间创建的复杂图表,而这些数据库很可能会被删除并重新创建的方式):

USE TargetDatabase

DELETE sysDiagrams
 where name in (select name from SourceDatabase.dbo.sysDiagrams)

SET identity_insert sysDiagrams on

INSERT sysDiagrams (name, principal_id, diagram_id, version, definition)
 select name, principal_id, diagram_id, version, definition
  from SourceDatabase.dbo.sysDiagrams

SET identity_insert sysDiagrams off

要将数据复制到另一个不同的SQL实例(或服务器)上,情况会更加困难。我使用临时创建的Linked Server定义,并使用多年以前费劲心血编写的脚本来修改它们(即发布不同的问题,以便知道如何操作),并使用适当的四部分命名约定修改脚本。其他选项(如OPENROWSET等)也可能可行,但我对它们的了解更少。


+1:这对我很有效。因为我在同一台服务器上,所以这并不是一个大问题,但在找到这个脚本之前,我还是有点苦恼。 - Brian MacKay

2
如果您想将图表从一个实例或服务器移动到另一个实例或服务器,而不想恢复整个数据库,可以按照以下步骤操作。
  1. If it doesn't exist, create the database on your target server. You also have to click on the "Database Diagrams" node in SSMS to have it create a dbo.sysDiagrams table.
  2. Then make sure to import all the schema information you need in your diagram. Because your diagram will point to these. I.e. tables, PK, FK etc. must be present.
  3. Backup your database on the source server.
  4. Restore it into a temporary database on the target server. In this way you get all your diagram information into the target server.
  5. Copy the information from the dbo.sysDiagrams table in the temporary database into the dbo.sysDiagram table of your target database. You could do something like this (adapted the code from Philip Kelley):

    USE TargetDatabase 
    
    SET identity_insert sysDiagrams on 
    
    INSERT sysDiagrams (name, principal_id, diagram_id, version, definition) 
     select name, principal_id, diagram_id, version, definition 
      from TempDatabase.dbo.sysDiagrams 
    
    SET identity_insert sysDiagrams off 
    

这个解决方案对我非常有效。当然,如果您不想要所有的图表或目标数据库中存在其他图表,则需要过滤选择语句并进行一些identity_insert操作,但这不应该太难。


0
为了移动数据库图表,您需要迁移该图表中包括的所有表和触发器。最简单的方法是备份数据库并在另一个服务器上进行恢复。

备份和恢复是我知道的迁移图表的唯一方法。 - DForck42
我不想进行备份和恢复,因为两个服务器上的表格不同。除了备份和恢复之外,还有其他方法吗? - user556674

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接