Unique Key Violation in SQL Server - Is it safe to assume Error 2627?

亡梦爱人 提交于 2019-11-26 12:42:53

问题


I need to catch violation of UNIQUE constraints in a special way by a C# application I am developing. Is it safe to assume that Error 2627 will always correspond to a violation of this kind, so that I can use

if (ThisSqlException.Number == 2627)
{
    // Handle unique constraint violation.
}
else
{
    // Handle the remaing errors.
}

?


回答1:


2627 is unique constraint (includes primary key), 2601 is unique index

SELECT * FROM sys.messages
WHERE text like '%duplicate%' and text like '%key%' and language_id = 1033



回答2:


Here is a handy extension method I wrote to find these:

    public static bool IsUniqueKeyViolation(this SqlException ex)
    {
        return ex.Errors.Cast<SqlError>().Any(e => e.Class == 14 && (e.Number == 2601 || e.Number == 2627 ));
    }



回答3:


Within an approximation, yes.

If you search the MS error and events site for SQL Server, error 2627, you should hopefully reach this page, which indicates that the message will always concern a duplicate key violation (note which parts are parameterized, and which not):

Violation of %ls constraint '%.*ls'. Cannot insert duplicate key in object '%.*ls'.


来源:https://stackoverflow.com/questions/6483699/unique-key-violation-in-sql-server-is-it-safe-to-assume-error-2627

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!