共用方式為


SqlException.Number 屬性

定義

取得識別錯誤類型的值。

public:
 property int Number { int get(); };
public int Number { get; }
member this.Number : int
Public ReadOnly Property Number As Integer

屬性值

識別錯誤類型的值。

範例

下列範例會顯示集合內的每一 SqlErrorSqlErrorCollection

using Microsoft.Data.SqlClient;
using System.Text;

class Program
{
    static void Main()
    {
        string s = GetConnectionString();
        ShowSqlException(s);
        Console.ReadLine();
    }

    public static void ShowSqlException(string connectionString)
    {
        string queryString = "EXECUTE NonExistantStoredProcedure";
        StringBuilder errorMessages = new StringBuilder();

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            try
            {
                command.Connection.Open();
                command.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                for (int i = 0; i < ex.Errors.Count; i++)
                {
                    errorMessages.Append("Index #" + i + "\n" +
                        "Message: " + ex.Errors[i].Message + "\n" +
                        "Error Number: " + ex.Errors[i].Number + "\n" +
                        "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                        "Source: " + ex.Errors[i].Source + "\n" +
                        "Procedure: " + ex.Errors[i].Procedure + "\n");
                }
                Console.WriteLine(errorMessages.ToString());
            }
        }
    }

    static private string GetConnectionString()
    {
        // To avoid storing the connection string in your code, 
        // you can retrieve it from a configuration file.
        return "Data Source=(local);Initial Catalog=AdventureWorks;"
            + "Integrated Security=SSPI";
    }
}

備註

這是 屬性中 Errors 第一個 SqlError 屬性的包裝函式 Number

如果 為 Errorsnull ,則會 default 傳回 的 int 值。

如需SQL Server引擎錯誤的詳細資訊,請參閱Database Engine 事件和錯誤

適用於

另請參閱