2011-11-04 36 views

回答

6

據我所知,沒有直接執行此操作的API - aspnet_regsql.exe工具無論如何都只是引用磁盤上的腳本文件。

了先機就如何落實這個自己:

您可以通過手動Process.Start執行aspnet_regsql.exe

或者您可以從命令行運行程序,並使用命令行選項來轉儲出腳本。然後將這些腳本編輯爲與數據庫不相關的腳本(或者不要 - 取決於您),將這些腳本作爲嵌入式資源存儲在您的應用程序中,在運行時將其解壓縮,然後使用SqlConnectionExecuteNonQuery對數據庫運行這些腳本。

以下是命令行選項aspnet_regsql.exe

http://msdn.microsoft.com/en-us/library/ms229862(v=vs.80).aspx

下面是一些代碼,我已經習慣了實現第二個選項:

ExecuteSqlScriptResource("MyDb", "MyAssemblyName.Scripts.aspnet_regsql_add.sql"); 

// ... 

static void ExecuteSqlScriptResource(string connectionName, string resourcePath) 
{ 
    using (Stream scriptStream = Assembly.GetExecutingAssembly() 
     .GetManifestResourceStream(resourcePath) 
     ) 
    { 
     if (scriptStream == null) 
     { 
      WriteLine(string.Format("Failed to open resource {0}", resourcePath)); 
      return; 
     } 

     using (
      var sqlConnection = new SqlConnection(
       ConfigurationManager 
        .ConnectionStrings[connectionName].ConnectionString 
       ) 
      ) 
     { 
      using (var streamReader = new StreamReader(scriptStream)) 
      { 
       var svrConnection = new ServerConnection(sqlConnection); 
       var server = new Server(svrConnection); 
       server.ConnectionContext.ExecuteNonQuery(streamReader.ReadToEnd()); 
      } 
     } 
    } 
} 
+1

-sqlexportlonly BAM! ty先生 – andrew

+0

@andrew:確實:)這不是數據庫不可知論者,如果這是你的關注。我手動編輯該文件。如果你想要一些slapped的代碼來執行這個腳本,我可以在今天晚些時候給你。大約10-15行。 –

+0

@andrew:很高興這有幫助。如果答案解決了您的問題,請將其標記爲已接受(答案左上方的複選標記)。 –