2013-04-26 155 views
7

是否可以從.NET爲SQL服務器數據庫生成數據庫創建腳本?生成數據庫創建腳本

我正在使用C#,我想爲我的應用程序 創建某種安裝程序項目,我可以在其中選擇現有數據庫,生成創建腳本並在另一個SQL Server實例上運行它們。

+0

你可以用'它被安裝爲項目模板的SQL Server開發Tools' http://www.develop.com/sqlservertwelvedatatools – praveen 2013-04-26 05:42:34

+1

你想動態生成數據庫? – 2013-04-26 05:56:51

+0

@raman,是的 - 動態。 – sTodorov 2013-04-26 06:15:21

回答

5

是的,這是可能的。 使用SMO可以很容易地完成此操作,請參閱Transfer用於腳本操作的類和用於數據庫操作(創建,刪除等)的Database類。用法如下所示:

private StringCollection GetTransferScript(Database database) 
    { 
     var transfer = new Transfer(database); 

     transfer.CopyAllObjects = true; 
     transfer.CopyAllSynonyms = true; 
     transfer.CopyData = false; 

     // additional options 
     transfer.Options.WithDependencies = true; 
     transfer.Options.DriAll = true; 
     transfer.Options.Triggers = true; 
     transfer.Options.Indexes = true; 
     transfer.Options.SchemaQualifyForeignKeysReferences = true; 
     transfer.Options.ExtendedProperties = true; 
     transfer.Options.IncludeDatabaseRoleMemberships = true; 
     transfer.Options.Permissions = true; 
     transfer.PreserveDbo = true; 

     // generates script 
     return transfer.ScriptTransfer(); 
    } 
0

您必須自己創建自己的安裝程序。那裏有框架,使它更容易。

  • 喜歡的Windows Installer XML(WiX的)
  • Windows安裝
  • 更多...

我建議你看看WiX的,用它和它很容易工作你可以做很多事情。可以集成在Visual Studio

1

,如果你想與當時這裏的C#代碼中動態創建數據庫的代碼是:

你能做到這樣也:

String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000); 

     SqlConnection con = new SqlConnection(); 
     con.ConnectionString = Connectionstring; 
     bool resultdbexistencx = CCMMUtility.CheckDatabaseExists(con, txt_DbName.Text); 
     if (!resultdbexistencx) 
     { 
      // if not exists create it check the user name for sub-admin avialibe or not. 

      if (txt_DbName.Text.Trim() == string.Empty) return; 

      string strDbCreate; 
      strDbCreate = "CREATE DATABASE " + txt_DbName.Text + " ON PRIMARY " + 
      "(NAME = " + txt_DbName.Text + "_Data, " + 
      "FILENAME = 'D:\\" + txt_DbName.Text + "Data.mdf', " + 
      "SIZE = 4MB, MAXSIZE = 10GB, FILEGROWTH = 100%) " + 
      "LOG ON (NAME = " + txt_DbName.Text + "_Log, " + 
      "FILENAME = 'D:\\" + txt_DbName.Text + ".ldf', " + 
      "SIZE = 4MB, " + 
      "MAXSIZE = 10GB, " + 
      "FILEGROWTH = 100%)"; 
      SqlConnection sqlconn = new SqlConnection(Connectionstring); 
      SqlCommand cmd = new SqlCommand(strDbCreate, sqlconn); 
      try 
      { 
       sqlconn.Open(); 
       sqlconn.ChangeDatabase("master"); 
       cmd.ExecuteNonQuery(); 
      } 
      catch (Exception ex) 
      { 
       Int32 dbRollbackResult = RollBackTheWholetransaction(txt_DbName.Text.Trim(), Convert.ToInt32(HospitalResult)); 
       if (dbRollbackResult == 1) 
       { 
        Response.Write(ex.Message); 
        lblMessage.DisplayMessage(StatusMessages.ErrorMessage, "There is some problem while generating the database or database name doesn't avialible."); 
       } 
      } 

這裏的代碼「RollBackTheWholetransaction」的方法:

private Int32 RollBackTheWholetransaction(String DbName, Int32 HospitalId) 
{ 
    Int32 result = 0; 
    try 
    { 
     String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000); 

     SqlConnection con = new SqlConnection(); 
     con.ConnectionString = Connectionstring; 

     String sqlCommandText = "ALTER DATABASE [" + DbName + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE"; 
     String sqlCommandText1 = "DROP DATABASE [" + DbName + "]"; 
     if (con.State == ConnectionState.Closed) 
     { 
      con.Open(); 
      SqlConnection.ClearPool(con); 
      con.ChangeDatabase("master"); 
      SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con); 
      sqlCommand.ExecuteNonQuery(); 
      SqlCommand sqlCommand1 = new SqlCommand(sqlCommandText1, con); 
      sqlCommand1.ExecuteNonQuery(); 

      ClsHospitals objHospiitals = new ClsHospitals(); 
      String resultDbdelete = objHospiitals.DeleteHospital(HospitalId, Session["devSuperAdmin"].ToString()); 
      if (resultDbdelete == "1") 
      { 
       result = 1; 
      } 
      else 
      { 
       result = 2; 
      } 
     } 
     else 
     { 
      SqlConnection.ClearPool(con); 
      con.ChangeDatabase("master"); 
      SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con); 
      sqlCommand.ExecuteNonQuery(); 
      SqlCommand sqlCommand1 = new SqlCommand(sqlCommandText1, con); 
      sqlCommand1.ExecuteNonQuery(); 
     } 
     con.Close(); 
     con.Dispose(); 
     result = 1; 
    } 
    catch (Exception ex) 
    { 
     result = 0; 
    } 
    return result; 
} 

這裏是檢查數據庫的存在於數據庫的代碼:

public static bool CheckDatabaseExists(SqlConnection tmpConn, string databaseName) 
{ 
    string sqlCreateDBQuery; 
    bool result = false; 

    try 
    { 
     // tmpConn = new SqlConnection("server=(local)\\SQLEXPRESS;Trusted_Connection=yes"); 



     sqlCreateDBQuery = string.Format("SELECT database_id FROM sys.databases WHERE Name = '{0}'", databaseName); 

     using (tmpConn) 
     { 
      using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn)) 
      { 
       if (tmpConn.State == System.Data.ConnectionState.Open) 
       { 
        tmpConn.Close(); 
        tmpConn.Dispose(); 
       } 
       tmpConn.Open(); 
       tmpConn.ChangeDatabase("master"); 
       int databaseID = (int)sqlCmd.ExecuteScalar(); 
       tmpConn.Close(); 

       result = (databaseID > 0); 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     result = false; 
    } 

    return result; 
} 

其工作代碼,希望它會爲你工作太....