在C#中高效率執行包含GO指令的大型SQL腳本
問題:
使用SqlCommand.ExecuteNonQuery()
執行包含多個由GO語句分隔的批次的大型SQL腳本具有挑戰性,因為它將GO解釋為無效語法。
解1:多個批次
一種方法是根據GO行將SQL腳本拆分為單一批次處理,並分別執行每個批次。雖然此方法有效,但對於大型腳本而言,它可能很繁瑣且容易出錯。
解決方案2:SQL Server Management Objects (SMO)
更有效的解決方案是利用SQL Server Management Objects (SMO),它原生支援GO指令分隔符號。
範例程式碼:
<code class="language-csharp">public static void Main() { // SQL连接字符串 string sqlConnectionString = "Integrated Security=SSPI;" + "Persist Security Info=True;Initial Catalog=Northwind;Data Source=(local)"; // 从目录获取SQL脚本 DirectoryInfo di = new DirectoryInfo("c:\temp\sqltest\"); FileInfo[] rgFiles = di.GetFiles("*.sql"); // 使用SMO执行每个脚本 foreach (FileInfo fi in rgFiles) { string script = File.ReadAllText(fi.FullName); using (SqlConnection connection = new SqlConnection(sqlConnectionString)) { Server server = new Server(new ServerConnection(connection)); server.ConnectionContext.ExecuteNonQuery(script); } } }</code>
附加庫:
另一個選擇是使用Phil Haack的函式庫,它封裝了使用GO分隔符號執行SQL腳本的功能:https://www.php.cn/link/3cdad14c5d7c1e1fa307772a876b42d7
以上是如何在C#中使用GO指令高效執行大型SQL腳本?的詳細內容。更多資訊請關注PHP中文網其他相關文章!