我想通过ADO.NET使用我的ASP.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语句在脚本中执行时会出现异常.我该如何解决这个问题?
解决方法
请参阅我关于
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); } } }