Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. } 

?

like image 852
User Avatar asked Jun 26 '11 11:06

User


People also ask

What is error number 2627 in SQL Server?

This issue occurs because the cached sequence is flushed incorrectly when you perform the database backup. This makes the value of the cached sequence larger than the value on the disk. In this situation, error 2627 is triggered.

How do you handle violation of unique key constraint?

To handle unique constraint violations: Catch uniqueness exceptions thrown by the database at the lowest level possible — in the UnitOfWork class. Convert them into Result.

What is violation of unique key constraint?

According to your situation. Violation of UNIQUE KEY constraint: [StudentID],[Section] is composite primary key and it should be unique. [SchoolID] should also be unique. So you are trying to insert values with same ([StudentID],[Section]).


2 Answers

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 
like image 191
gbn Avatar answered Oct 22 '22 09:10

gbn


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 ));     } 
like image 32
jhilden Avatar answered Oct 22 '22 10:10

jhilden