How to execute an .SQL script file using c#

后端 未结 10 811
忘了有多久
忘了有多久 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:40

    I tried this solution with Microsoft.SqlServer.Management but it didn't work well with .NET 4.0 so I wrote another solution using .NET libs framework only.

    string script = File.ReadAllText(@"E:\someSqlScript.sql");
    
    // split script on GO command
    IEnumerable commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
    
    Connection.Open();
    foreach (string commandString in commandStrings)
    {
        if (!string.IsNullOrWhiteSpace(commandString.Trim()))
        {
            using(var command = new SqlCommand(commandString, Connection))
            {
                command.ExecuteNonQuery();
            }
        }
    }     
    Connection.Close();
    

提交回复
热议问题