2009-07-27 90 views
6

我想通過ADO.NET使用ASP.NET網站運行我的.sql腳本文件。它怎麼可能不起作用?如何通過ADO.NET運行我的.sql腳本文件?

當我嘗試

'dbScript is a string and contains contents of the .sql file' 
Dim cmd As New SqlCommand(dbScript, con) 
Try 
    con.Open() 
    cmd.ExecuteNonQuery() 
Catch ex As Exception 
Finally 
    con.Close() 
    cmd.Dispose() 
End Try 

我得到異常時,GO語句執行腳本。我該如何解決這個問題?

回答

13

見我的博客文章Handling GO Separators in SQL - The Easy Way。訣竅是使用SMO's ExecuteNonQuery()方法。例如,這裏的一些代碼,將在目錄中運行的所有腳本,無論GO分隔符:

using System; 
    using System.IO; 
    using System.Data.SqlClient; 
    using System.Collections.Generic; 

    //Microsoft.SqlServer.Smo.dll 
    using Microsoft.SqlServer.Management.Smo; 
    //Microsoft.SqlServer.ConnectionInfo.dll 
    using Microsoft.SqlServer.Management.Common; 

    public class RunAllSqlSriptsInDirectory 
    { 
     public static void Main() 
     { 
      string scriptDirectory = "c:\\temp\\sqltest\\"; 
      string sqlConnectionString = "Integrated Security=SSPI;" + 
       "Persist Security Info=True;Initial Catalog=Northwind;Data Source=(local)"; 
      DirectoryInfo di = new DirectoryInfo(scriptDirectory); 
      FileInfo[] rgFiles = di.GetFiles("*.sql"); 
      foreach (FileInfo fi in rgFiles) 
      { 
       FileInfo fileInfo = new FileInfo(fi.FullName); 
       string script = fileInfo.OpenText().ReadToEnd(); 
       SqlConnection connection = new SqlConnection(sqlConnectionString); 
       Server server = new Server(new ServerConnection(connection)); 
       server.ConnectionContext.ExecuteNonQuery(script); 
      } 
     } 
    } 
+5

請注意,依賴SMO將需要您的應用程序預先安裝SMO可再發行組件,這是一個小的不便。但真正的交易殺手是SMO是特定於版本的,並且將拒絕連接到更高版本的SQL:使用SQL 2k5中的SMO開發的應用程序將不會連接到SQL Server 2k8,因此需要開發人員發佈新的使用SMO 2k8的應用程序版本。 – 2009-07-27 23:08:31

7

GO不是Transact-SQL語句,是一個工具批量分隔符。當在批處理中遇到GO時,服務器正確地抱怨語法錯誤。您需要將文件分成批次,然後執行單個批次。使用正則表達式分割文件inot批次,並在單行上識別GO不區分大小寫。

2

這是因爲GO實際上並不是一個本地TSQL語句,它在Management Studio/Enterprise Manager中用於將腳本劃分爲批處理。

你要麼需要:
1)將其分割成每個多個獨立的腳本GO聲明
2)使用SQL Management中的Server類對象,如所示例here

3

沒有用分裂法來執行批次一個小問題。問題是評論。假設你對文件的內容沒有權力。你只需要執行它。在多行註釋中進行GO將是每個解決方案示例中的問題,這裏將使用「GO」作爲分隔符來分割sql代碼。例如:

[some sql code] 
GO 

/* start of commented out sql code *********** 
[some sql code] 
GO 
end of commented out sql code ****************/ 

[some sql code] 
GO 

這將需要一些比拆分更復雜的解析。這將不再有效:

Regex regex = new Regex("^GO", RegexOptions.IgnoreCase | RegexOptions.Multiline); 
string[] lines = regex.Split(sql); 

此代碼也忽略空格可能導致GO。

0

你將不得不做兩次通過解析。第一次通過是刪除所有的評論,並建立一個新的字符串。第二遍是使用基於GO關鍵字的REGEX拆分。