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();
}
}
SMOmsdn.microsoft.com/en-us/library/ms162169(v=sql.105).aspx