"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to execute SQL script files containing multiple statements in C#?

How to execute SQL script files containing multiple statements in C#?

Posted on 2025-04-16
Browse:456

How Can I Execute an SQL Script File Containing Multiple Statements in C#?

Executing SQL Script Files with C# Using SMO

This guide demonstrates how to execute SQL script files containing multiple statements (potentially spanning several lines) within a C# application. We'll leverage the Microsoft SQL Server Management Objects (SMO) for this task.

Here's a C# code example:

using System;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.IO;

public class SqlScriptRunner
{
    public void RunScript(string scriptPath, string connectionString)
    {
        // Read the entire SQL script from the file.
        string sqlScript = File.ReadAllText(scriptPath);

        // Establish a database connection.
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            // Create a Server object using the connection.
            Server server = new Server(new ServerConnection(connection));

            // Execute the script using SMO's ExecuteNonQuery.
            server.ConnectionContext.ExecuteNonQuery(sqlScript);
        }
    }
}

Implementation Steps:

  1. Add SMO Reference: Include the Microsoft.SqlServer.Management.Smo and Microsoft.SqlServer.Management.Common assemblies in your project's references.
  2. Instantiate and Execute: Create an instance of SqlScriptRunner and call the RunScript method, providing the full path to your SQL script file and a valid database connection string.

This method offers a clean and efficient way to handle complex SQL scripts within your C# applications. The using statement ensures proper resource management by automatically closing the database connection.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3