Wrap the ExecuteNonQuery in a try/catch block and leave the catch block empty.
Ignore error in executing SQL Script
-
30-05-2022 - |
Question
How can I make my code ignore the error while executing SQL Script file?
If there is an error while executing the sql script file, then I want this method to just ignore it and continue to run the sql script file. Currently, if I put try-catch block inside this method, the error gets caught as an exception and the execution of the SQL script file stops after the error has been caught. I want the execution to continue even if there is an error in the SQL Server.
How can I achieve this?
My code is below.
private void RunSQLScript()
{
// file is already defined as a SQL Script file
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(ConnectionString);
// split script on GO command
IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
conn.Open();
foreach (string commandString in commandStrings)
{
if (commandString.Trim() != "")
{
new SqlCommand(commandString, conn).ExecuteNonQuery();
}
}
conn.Close();
}
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow