在C#中捕获SQL Server双消息错误

时间:2014-01-28 00:06:46

标签: c# sql-server

SQL Server中有几个语句会抛出多个错误。一个示例是具有不完整的列级权限的select语句。假设你有这样的设置

CREATE USER TestUser1 WITHOUT LOGIN;
CREATE TABLE dbo.tst(id INT, c1 INT, c2 INT);
GRANT SELECT ON dbo.tst(id) TO TestUser1;

如果现在,作为TestUser1,在SQL Server Management Studio中执行简单的SELECT * FROM dbo.tst;,则会返回两条消息:

Msg 230, Level 14, State 1, Line 1
The SELECT permission was denied on the column 'c1' of the object 'tst', database 'tempdb', schema 'dbo'.
Msg 230, Level 14, State 1, Line 1
The SELECT permission was denied on the column 'c2' of the object 'tst', database 'tempdb', schema 'dbo'.

但是,如果我执行类似下面的操作,我总是只会收到第一个错误:

    try
    {
        using (var conn = new SqlConnection("context connection=true;"))
        {
            try
            {
                var sqlCommand = new SqlCommand {CommandText = cmd.ToString(), Connection = conn};
                conn.Open();
                var r = sqlCommand.ExecuteReader();
            }
            finally
            {
                conn.Close();
            }
        }
    }
    catch (SqlException e)
    {
        SqlContext.Pipe.Send(e.Message+"\n");
    }
    return 0;
}

SQL Server Management Studio显示两个错误,因此似乎有一种捕获这两种消息的方法。

嗯,那个方法是什么?

1 个答案:

答案 0 :(得分:1)

有一个错误属性集合附加到SqlException对象。

    for (int i = 0; i < e.Errors.Count; i++)
    {
        Console.WriteLine("Index #" + i + "\n" +
            "Error: " + e.Errors[i].ToString() + "\n");
    }

遍历此集合将为您提供所有错误......