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

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

DDD
Release: 2025-01-20 01:56:09
Original
371 people have browsed it

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

Efficiently Running Large SQL Scripts with GO Commands in C#

Database management often involves executing SQL scripts containing GO commands to separate batches. Directly using SqlCommand.ExecuteNonQuery() presents challenges when dealing with these scripts.

Leveraging SQL Server Management Objects (SMO)

A robust approach utilizes SQL Server Management Objects (SMO). SMO inherently handles GO separators, simplifying script execution. The ServerContext class within SMO provides a straightforward method for this purpose.

Here's an example using SMO:

<code class="language-csharp">using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

// Establish a connection to the SQL Server instance
using (SqlConnection connection = new SqlConnection(sqlConnectionString))
{
    // Create a Server object
    Server server = new Server(new ServerConnection(connection));

    // Execute the SQL script
    server.ConnectionContext.ExecuteNonQuery(script);
}</code>
Copy after login

Alternative Solution: Haacked's Library

If SMO isn't feasible, Phil Haack's library offers an alternative for managing GO statements:

<code class="language-csharp">using Haacked.Sql;

// Execute the script using Haacked's library
BatchScript.Run(sqlConnectionString, script);</code>
Copy after login

Summary

SMO or Haack's library provide efficient and reliable methods for executing large SQL scripts containing GO commands in C#, eliminating the complexities of manual batch separation. Choose the method best suited to your project's dependencies and requirements.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template