小编典典

如何通过ADO.NET运行.sql脚本文件?

sql

我想使用我的ASP.NET网站通过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语句时出现异常。我该如何解决这个问题?


阅读 294

收藏
2021-03-17

共1个答案

小编典典

请参阅我的博客文章,其中介绍了如何使用SQL-Easy
Way处理GO分隔符
。诀窍是使用SMO的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);
            }
        }
    }
2021-03-17