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

后端 未结 4 1672
不知归路
不知归路 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 08:58

    You could do it this way as well:

    var result = DbCon.CheckForPrimaryKey(value).ToList();
    if(result.Count() == 0)
           DbCon.InsertValue(value);
    else
         // Do Nothing   
    
    0 讨论(0)
  • 2020-12-09 09:00

    What you are looking for is a SqlException, specifically the violation of primary key constraints. You can get this specific error out of this exception by looking at the number property of the exception thrown. This answer is probably relevant to what you need: How to Identify the primary key duplication from a SQL Server 2008 error code?

    In summary, it looks like this:

    // put this block in your loop
    try
    {
       // do your insert
    }
    catch(SqlException ex)
    {
       // the exception alone won't tell you why it failed...
       if(ex.Number == 2627) // <-- but this will
       {
          //Violation of primary key. Handle Exception
       }
    }
    

    EDIT:

    This may be a bit hacky, but you could also just inspect the message component of the exception. Something like this:

    if (ex.Message.Contains("UniqueConstraint")) // do stuff
    
    0 讨论(0)
  • 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...
       }
    }
    
    0 讨论(0)
  • 2020-12-09 09:09

    You could wrap the insert into a stored procedure that first validated there was no duplicates before inserting. That way, you can control exactly what comes back when the value is duplicated.

    Additionally, you may find that shifting the insert logic into an SP will allow you do do the bulk insert that you appear to be doing without making repeated calls the the DB.

    For an answer to your actual question:

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

    0 讨论(0)
提交回复
热议问题