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
You could do it this way as well:
var result = DbCon.CheckForPrimaryKey(value).ToList();
if(result.Count() == 0)
DbCon.InsertValue(value);
else
// Do Nothing
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
In addition of Bill Sambrone's answer,
Two error codes are used to check unique key violation
2601 - Violation in unique index
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...
}
}
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?