0

I am trying to execute multiple SQL scripts in a single file from C#. In between the scripts I have GO statements. the script is like an incremental script and day by day that script will increase. I tried using ExecuteReader(), ExecuteScalar() and ExecuteNonQuery(), but it was throwing exception saying GO is incorrect syntax.

I then split the script with GO and in a loop, I tried to execute there also where ever script will have Declare @xyz DataType it throwing an exception.

Please suggest how I can execute such script from C#.

foreach (var sqlBatch in ScriptDetails.Split(new[] { "GO", "Go", "go", "gO" }, StringSplitOptions.RemoveEmptyEntries))
{
    try
    {
        string[] prefixes = { "--", "/*" };
        bool resultchk = prefixes.Any(prefix => sqlBatch.StartsWith(prefix));
        if (!resultchk)
        {
            connection.Open();
            command.CommandText = sqlBatch;
            command.ExecuteNonQuery();//ExecuteReader(); ExecuteScalar()
            connection.Close();
            Result.Add(new SQLResult { Final_message = "Success" });
        }
    }
    catch (SqlException ex)
    {
        Result.Add(new SQLResult { Final_message = ex.Message.ToString(), Line_No = ex.LineNumber });
        connection.Close();
    }
}
2
  • 1
    you can use SMO msdn.microsoft.com/en-us/library/ms162169(v=sql.105).aspx Commented Apr 4, 2018 at 5:11
  • 1
    SMO are an additional effort to deploy (especially when you have to support different SQL Server versions). I wouln't use SMO just to run SQL Scripts. Commented Apr 4, 2018 at 6:54

1 Answer 1

1

I would try to open the connection only once to run all the parts of the script.

Pseudo-code:

use (var connection ...)
{
  connection.Open();
  foreach (var sqlBatch in ...)
  {
    use (var command = new Command(..., connection))
    {
      command.CommandText = sqlBatch;
      ...
      command.ExecuteNonQuery();
    }
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Also a transaction implementation might be helpful. Just a thought. ;-)
@shadow: Hard to say. Most scripts are doing transaction themselves. But it's certainly a good point to consider.
Thank you @Stefan Steinegger

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.