2013-06-12 99 views
1

我正在尝试使用SQL Server管理对象(SMO)Transfer类创建表(无数据,只是模式)的副本。我唯一没有想到的是如何指定服务器在不同主机上时要复制到哪个服务器。在我的情况下,我想从10.1.2.x复制到10.1.2.y.有什么方法可以指定这个,或者这个类不支持它吗?将表从一个SQL Server复制到另一个

也许有更好的C#解决方案?

static void CreateTableFromTable(string fromConnection, string toConnection, string dbName, string tablename, bool copyData = false) 
{ 
    Server fromServer = new Server(new ServerConnection(new SqlConnection(fromConnection))); 
    Database db = fromServer.Databases[dbName]; 

    Transfer transfer = new Transfer(db); 
    transfer.CopyAllObjects = false; 
    transfer.DropDestinationObjectsFirst = false; 
    transfer.CopySchema = false; //Database schema? Or Table schema? I DO NOT want to overwrite the db schema 
    transfer.CopyData = copyData; 
    transfer.DestinationServer = "?"; 
    transfer.DestinationDatabase = dbName; 
    transfer.Options.IncludeIfNotExists = true; 
    transfer.ObjectList.Add(db.Tables[tablename]); 

    transfer.TransferData(); 
} 

回答

-2

您是否尝试过使用SELECT ... INTO声明?

例如:

SELECT * INTO DestDatabase.TableName FROM SourceDatabase.TableName 

如果你不想复制数据时,只需添加这将返回任何一个条件,例如:WHERE Id = 0

+0

如何指定包含数据库的服务器的IP地址? – SamiHuutoniemi

+0

只需将它放在

+0

如何?这不像我可以键入SELECT * INTO DestDatabase.TableName FROM 10.1.2.1.SourceDatabase.TableName – SamiHuutoniemi

1

您是否尝试过进口和出口数据甚至精灵使用SQL Server 2005/8和Mysql/MysqlWorkbench中的表数据,命令行或GUI进行导入。

0

我不确定你是否找到了另一个解决方案 - 或者得到了这个解决方案。如果您没有SMO Scripter对象可能值得一看。

This MSDN例子可能会有帮助。您可以编写所需的表和依赖关系,然后打开到目标数据库的连接并执行脚本。

static void Main(string[] args) 
{ 
    Server sourceServer = new Server("server"); 
    String dbName = "database"; 

    // Connect to the local, default instance of SQL Server. 

    // Reference the database. 
    Database db = sourceServer.Databases[dbName]; 

    // Define a Scripter object and set the required scripting options. 
    Scripter scripter = new Scripter(sourceServer); 
    scripter.Options.ScriptDrops = false; 
    scripter.Options.WithDependencies = true; 
    scripter.Options.Indexes = true; // To include indexes 
    scripter.Options.DriAllConstraints = true; // to include referential constraints in the script 

    // Iterate through the tables in database and script each one. Display the script. 
    foreach (Table tb in db.Tables) 
    { 
     // check if the table is not a system table 
     if (tb.IsSystemObject == false) 
     { 
      Console.WriteLine("-- Scripting for table " + tb.Name); 

      // Generating script for table tb 
      System.Collections.Specialized.StringCollection sc = scripter.Script(new Urn[] { tb.Urn }); 
      foreach (string st in sc) 
      { 
       //ado.net to destination 
       Console.WriteLine(st);//SqlCommand.ExecuteNonQuery(); 
      } 
      Console.WriteLine("--"); 
     } 
    } 
} 
相关问题