Home >Backend Development >C++ >How to Execute Large SQL Scripts with GO Commands in C#?

How to Execute Large SQL Scripts with GO Commands in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-20 01:51:10968browse

How to Execute Large SQL Scripts with GO Commands in C#?

Use GO command to execute large SQL scripts

Question: How to execute a large SQL script containing GO commands in a C# program? SqlCommand.ExecuteNonQuery() does not recognize the GO statement.

Answer: Use SQL Server Management Objects (SMO) that recognizes the GO delimiter.

Sample code:

<code class="language-csharp">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();
        using (SqlConnection connection = new SqlConnection(sqlConnectionString))
        {
            Server server = new Server(new ServerConnection(connection));
            server.ConnectionContext.ExecuteNonQuery(script);
        }
    }
}</code>

Alternative library options:

As an alternative, you might consider Phil Haack's library specifically for handling SQL scripts containing GO delimiters: https://www.php.cn/link/1288625a4bdcf1109ff5adca3bd33753

The above is the detailed content of How to Execute Large SQL Scripts with GO Commands in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn