Best way to catch sql unique constraint violations in c# during inserts

后端 未结 4 1686
不知归路
不知归路 2020-12-09 08:48

I have a loop in c# that inserts into a table. pretty basic stuff. Is there something insdie the exception object that\'s thrown when a unique constraint is violated that i

4条回答
  •  没有蜡笔的小新
    2020-12-09 09:07

    In addition of Bill Sambrone's answer,

    Two error codes are used to check unique key violation

    1. 2601 - Violation in unique index
    2. 2627 - Violation in unique constraint (although it is implemented using unique index)

    Either you can use one or both according to your needs:

    try
    {
    
    }
    catch(SqlException ex)
    {
       if(ex.Number == 2601) 
       {
          // Violation in unique index
       }
       else if(ex.Number == 2627)
       {
          // Violation in unique constraint
       }
    }
    

    OR

    try
    {
    
    }
    catch(SqlException ex)
    {
       if(ex.Number == 2601 || ex.Number == 2627)
       {
          // Violation in one on both...
       }
    }
    

提交回复
热议问题