How to execute sql script from C#

  • Hi Guys,

    I have this code to execute a sql script in C#. It works great but I'm not happy with the dependency on the following. If the PC I want to run this on has no SQL Server installed this will fail. I need a better way. It needs to work for scripts that have GO statements in them as well.

    using Microsoft.SqlServer.Management.Smo;

    using Microsoft.SqlServer.Management.Common;

    if (File.Exists(filePath))

    {

    FileInfo file = new FileInfo(filePath);

    string script = file.OpenText().ReadToEnd();

    using (SqlConnection conn = new SqlConnection(connectionString))

    {

    Server server = new Server(new ServerConnection(conn));

    ReturnValue = server.ConnectionContext.ExecuteNonQuery(script);

    }

    file.OpenText().Close();

    }

  • Do you really need to install the entire SQL Server? I think the SQL client alone is probably enough.

    The GO statement is not a T-SQL statement, but a batch seperator for SSMS and SQLCMD.

    It will not work outside those environments.

    Need an answer? No, you need a question
    My blog at https://sqlkover.com.
    MCSE Business Intelligence - Microsoft Data Platform MVP

  • you can explicitly extract both those DLLs from the GAC(Global Assembly Cache), and then make sure they are in your bin folder with the executable you are calling.

    in that way, your references are available, without having to install SQL on the machine it is executed from.

    the problem, of course, is you need someone to select the target server with the appropriate permissions., and split the document up into multiple separate commands based on the GO statement, and execute each of those commands in a loop.

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply