среда, 23 июля 2008 г.

Execute T-SQL script from C# code

if (filename.Length > 0)
{
try
{
// Open the file to read from.
using (StreamReader sr = File.OpenText(filename))
{
string queryString = sr.ReadToEnd().Replace("GO", "");

using (SqlConnection connection = new SqlConnection(ASSettings.ConnectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
MessageBox.Show("Script executed.", "Result", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("Error script execution!\n" + ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}