我正在尝试使用SQL Server管理对象(SMO)Transfer类创建表的副本(无数据,只是模式)。我唯一没想到的是当服务器在不同的主机上时,如何指定要复制到的服务器。就我而言,我想从10.1.2.x复制到10.1.2.y.有没有办法指定这个,还是这个类不支持它?
也许有更好的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();
}
答案 0 :(得分:1)
您是否尝试过导入和导出数据向导,甚至在SQL Server 2005/8和Mysql / MysqlWorkbench中使用表数据,命令行或GUI导入。
答案 1 :(得分:0)
我不确定你是否找到了另一个解决方案 - 或者让这个解决方案正常工作。如果你没有SMO Scripter对象可能值得一看。
此 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("--");
}
}
}
答案 2 :(得分:-2)
您是否尝试使用SELECT ... INTO
声明?
例如:
SELECT * INTO DestDatabase.TableName FROM SourceDatabase.TableName
如果您不想复制数据,只需添加一个不返回的条件,例如:WHERE Id = 0