sql-server - 如何将所有模式从一个数据库复制到另一个数据库(在运行时创建)?
问题描述
我已经为一个数据库的表使用了模式,所以如何将所有模式从一个数据库复制到另一个数据库(在运行时创建的数据库)
string sql = "create database " + str1;
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
command.ExecuteNonQuery();
Response.Write("database created");
connection.Close();
string sqll = "(select * into " + str1 + ".cost_category.cost_category_info
from ERPAccounting.cost_category.cost_category_info where 1=2)
(select * into " + str1 + ".dbo.cost_centre_info from
ERPAccounting.cost_centre.cost_centre_info where 1=2)"
connection.Open();
SqlDataAdapter ad = new SqlDataAdapter(sqll, connection);
DataSet ds = new DataSet();
ad.Fill(ds);
解决方案
使用C#,可以使用SMO
对象获取对象DDL,然后在需要将对象复制到的数据库中执行。在下面的示例中,对 、 和 的引用Microsoft.SqlServer.Management.Smo,
Microsoft.SqlServer.ConnectionInfo
是Microsoft.SqlServer.Management.Sdk.Sfc
必要System.Data.SqlClient
的。DDL 首先从 SMO 对象中获取,然后用作CommandText
在SqlCommand
目标数据库中执行的对象。此示例适用于表,但也可以使用此方法复制其他对象(视图、存储过程等)。
//set initial catalog to destination database
string connStr = @"Data Source=YourServer;Initial Catalog=DestinationDatabase;Integrated Security=SSPI;";
using (SqlConnection conn = new SqlConnection(connStr))
{
//set source server and database using SMO objects
Server srv = new Server(@"YourServer");
srv.ConnectionContext.LoginSecure = true;
srv.ConnectionContext.StatementTimeout = 600;
Database db = srv.Databases["SourceDatabase"];
//configure Scripter for DDL
Scripter script = new Scripter(srv);
ScriptingOptions scriptOpt = new ScriptingOptions();
//SQL command to execute DDL in destination database
SqlCommand sql = new SqlCommand();
sql.Connection = conn;
conn.Open();
//this can changed to views, SPs, etc. as needed
foreach (Table t in db.Tables)
{
//check for system objects
if (!t.IsSystemObject)
{
StringCollection sc = t.Script(scriptOpt);
foreach (string s in sc)
{
//assign and execute DDL
sql.CommandText = s;
sql.ExecuteNonQuery();
}
}
}
}
推荐阅读
- python - Python修改函数内部的全局变量
- pandas - 将列标题转换为索引
- python - python.exe - FastCGI 进程意外退出
- git - git同一个项目,两个单独的repos - 如何合并在一起
- c# - 是否可以务实地设置输出类型?或者如何添加 PropertyGroup 条件?
- python - FileNotFound Exception 在 Python 中以 wb 模式打开文件
- tensorflow - 使用机器学习去除手写签名图像中的背景
- python - 在 Python 中使 for 循环更快
- android - Android 通知:如何显示粘滞/更新警报
- php - 如何将数组传递给 ::with() - Lumen/Laravel