I execute SQL scripts to change the database schema. It looks something like this:
using (var command = connection.CreateCommand())
{
command.CommandText = script;
command.ExecuteNonQuery();
}
Additionally, the commands are executed within a transaction.
The scrip looks like this:
Alter Table [TableName]
ADD [NewColumn] bigint NULL
Update [TableName]
SET [NewColumn] = (SELECT somevalue FROM anothertable)
I get an error, because NewColumn
does not exist. It seems to parse and validate it before it is executed.
When I execute the whole stuff in the Management Studio, I can put GO
between the statements, then it works. When I put GO
into the script, ADO.NET complains (Incorrect syntax near 'GO').
I could split the script into separate scripts and execute it in separate commands, this would be hard to handle. I could split it on every GO
, parsing the script myself. I just think that there should be a better solution and that I didn't understand something. How should scripts like this be executed?
My implementation if anyone is interested in, according to John Saunders' answer:
List<string> lines = new List<string>();
while (!textStreamReader.EndOfStream)
{
string line = textStreamReader.ReadLine();
if (line.Trim().ToLower() == "go" || textStreamReader.EndOfStream)
{
ExecuteCommand(
string.Join(Environment.NewLine, lines.ToArray()));
lines.Clear();
}
else
{
lines.Add(line);
}
}