How to execute an .SQL script file using c#

后端 未结 10 894
忘了有多久
忘了有多久 2020-11-22 17:03

I\'m sure this question has been answered already, however I was unable to find an answer using the search tool.

Using c# I\'d like to run a .sql file. The sql file

10条回答
  •  醉梦人生
    2020-11-22 17:41

    Added additional improvements to surajits answer:

    using System;
    using Microsoft.SqlServer.Management.Smo;
    using Microsoft.SqlServer.Management.Common;
    using System.IO;
    using System.Data.SqlClient;
    
    namespace MyNamespace
    {
        public partial class RunSqlScript : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                var connectionString = @"your-connection-string";
                var pathToScriptFile = Server.MapPath("~/sql-scripts/") + "sql-script.sql";
                var sqlScript = File.ReadAllText(pathToScriptFile);
    
                using (var connection = new SqlConnection(connectionString))
                {
                    var server = new Server(new ServerConnection(connection));
                    server.ConnectionContext.ExecuteNonQuery(sqlScript);
                }
            }
        }
    }
    

    Also, I had to add the following references to my project:

    • C:\Program Files\Microsoft SQL Server\120\SDK\Assemblies\Microsoft.SqlServer.ConnectionInfo.dll
    • C:\Program Files\Microsoft SQL Server\120\SDK\Assemblies\Microsoft.SqlServer.Smo.dll

    I have no idea if those are the right dll:s to use since there are several folders in C:\Program Files\Microsoft SQL Server but in my application these two work.

提交回复
热议问题