I am developing a program for my final project of college that consists of taking several SQL scripts from a fixed folder and executing them. In a meeting with my project supervisor he said that it would be a good idea to make sure that if an error is detected while running one of the scripts the program should stop running the script and stop. And i'm having problems with the part of stopping the program after it detects the error. Help would be very appreciated. Btw this is all done in C# (WindowsFormsApp(.NET Framework)). The script that i'm showing works perfectly.
public string ExecuteFiles(string connectionString, string fileName)
{
var result = string.Empty;
//var error = ">> [" + MethodBase.GetCurrentMethod().Name + "]\n";
try
{
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Updates", fileName);
string script = File.ReadAllText(path);
using (SqlConnection connection = new SqlConnection(connectionString))
{
Logger.Debug("Script a ser executado: " + fileName);
connection.Open();
Server server = new Server(new Microsoft.SqlServer.Management.Common.ServerConnection(connection));
server.ConnectionContext.ExecuteNonQuery(script);
Logger.Debug("Script executado: " + fileName);
}
}
catch (Microsoft.SqlServer.Management.Common.ConnectionFailureException cfe)
{
Logger.Error("Message: " + cfe);
lblmsg.Text = ">> [Message] => " + cfe.Message + "\n";
}
catch (SmoException se)
{
Logger.Error("Message: " + se);
lblmsg.Text = ">> [Message] => " + se.Message + "\n";
}
catch (Exception ex)
{
Logger.Error("Message: " + ex);
lblmsg.Text = ">> [Message] => " + ex.Message + "\n";
if (ex.InnerException is SqlException)
{
SqlException sqlex = (SqlException)ex.InnerException;
lblmsg.Text = ">> [Message] => " + sqlex.Message + "\n";
Logger.Error("Message: " + sqlex);
}
}
return result;
}