Unique key violation in SQL Server. Can error 2627 be assumed?

I need to break UNIQUE restrictions in a special way with the C # application that I am developing. Is it possible 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. } 

?

+53
sql-server-2005 unique-constraint
Jun 26 2018-11-11T00:
source share
3 answers

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

 SELECT * FROM sys.messages WHERE text like '%duplicate%' and text like '%key%' and language_id = 1033 
+95
Jun 26 '11 at 12:19
source share

Here is a handy extension method that I wrote to find them:

  public static bool IsUniqueKeyViolation(this SqlException ex) { return ex.Errors.Cast<SqlError>().Any(e => e.Class == 14 && (e.Number == 2601 || e.Number == 2627 )); } 
+8
Dec 18 '15 at 18:41
source share

In the approximation, yes.

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

 Violation of %ls constraint '%.*ls'. Cannot insert duplicate key in object '%.*ls'. 
+3
Jun 26 '11 at 11:52
source share



All Articles