2009-07-27 85 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拆分。