首页 > 解决方案 > 如何将所有模式从一个数据库复制到另一个数据库(在运行时创建)?

问题描述

我已经为一个数据库的表使用了模式,所以如何将所有模式从一个数据库复制到另一个数据库(在运行时创建的数据库)

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);

标签: sql-server

解决方案


使用C#,可以使用SMO对象获取对象DDL,然后在需要将对象复制到的数据库中执行。在下面的示例中,对 、 和 的引用Microsoft.SqlServer.Management.Smo, Microsoft.SqlServer.ConnectionInfoMicrosoft.SqlServer.Management.Sdk.Sfc必要System.Data.SqlClient的。DDL 首先从 SMO 对象中获取,然后用作CommandTextSqlCommand目标数据库中执行的对象。此示例适用于表,但也可以使用此方法复制其他对象(视图、存储过程等)。

            //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();
                        }
                    }
                }
            }

推荐阅读