如何通过SQL Server捕获异常来控制程序?

时间:2017-07-06 08:35:35

标签: c# sql-server exception

for(int i=0; i < fileDirectories.Count;i++){

string script = File.ReadAllText(@fileDirectories[i]);
string[] singleCommand = Regex.Split(script,"^GO", RegexOptions.Multiline);
StringCollection scl = new StringCollection();

foreach(string t in singleCommand){
    if(t.Trim().Length > 0) scl.Add(t.Trim());
}

try
{
    int[] result = Server
               .ConnectionContext
               .ExecuteNonQuery(scl, ExecutionTypes.ContinueOnError);
}catch(Exception e)
{
//whatever
}
}

此程序的目标是运行多个脚本,如果失败,则捕获SQL SERVER抛出的异常并继续运行其余脚本。

为了试用,INSERT PERMISSION已被从DB中删除,因此在SQL SERVER上手动执行时,第一次查询(INSERT查询)将失败,因为INSERT PERMISSION已被带走以下错误

The INSERT permission was denied on object 'xxx',database 'xxxxx', schema 'xx'

运行程序时,变量result将具有值0,表示查询失败,但是它不会抛出错误并在catch处捕获?我应该如何将SQL Server提供的异常传递给我的控制台程序?

2 个答案:

答案 0 :(得分:1)

删除ExecutionTypes.ContinueOnError

将执行类型设置为ContinueOnError时,不会抛出异常。

try
{
      int[] result = Server.ConnectionContext
                    .ExecuteNonQuery(stringColleciton);
}
catch(SqlException se)
{
      //write log, show message
}
catch(Exception e)
{
      //write log, show message
}

关于ServerConnection.ExecuteNonQuery Method (String, ExecutionTypes)

,请阅读here

答案 1 :(得分:1)

您可以使用

public int ExecuteNonQuery(
    string sqlCommand,
    ExecutionTypes executionType
)

而不是

public int[] ExecuteNonQuery(
    StringCollection sqlCommands,
    ExecutionTypes executionType
)

例如

foreach (string t in singleCommand)
        {
            if (t.Trim().Length > 0)
            {
                try
                {
                    // do not use ExecutionTypes.ContinueOnError, it will not
                    // throw any exceptions
                    int result = Server
                        .ConnectionContext
                        .ExecuteNonQuery(t, ExecutionTypes.Default); 
                }
                catch (ExecutionFailureException ex) 
                {
                    // do anything
                    // do not throw error here
                }
                catch (Exception e)
                {
                    // do anything
                    // do not throw error here
                }
            }
        }