Monday, March 24, 2008

Programmatically Executing SQL Scripts

I didn't realize GO is not a SQL keyword. When I was trying to execute a script that worked in SQL Server Management Studio I was getting SQLException Incorrect syntax near 'Go'. The solution is to split the input script on GOs and execute those scripts.

const char splitChar = '☻'; //this character should never appear in command files
if (createDatabaseScript.Contains(splitChar.ToString()) == true)
throw new Exception("Aborting. Splitting this file may break the script because the script contains the split character");
using (dbConnnection)
{
dbConnnection.Open();
SqlCommand createDbCommand = new SqlCommand(string.Empty, dbConnnection);

//split the input script into multiple scripts based on GOs
foreach (string command in createDatabaseScript.Replace("GO", splitChar.ToString()).Split(new Char[] { splitChar }))
{
try
{
createDbCommand.CommandText = command;
createDbCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
//log the error for later review.
results += ex.Message + Environment.NewLine;
}
}
}
Console.Write(results);

No comments: