在插入期间捕获c#中sql唯一约束违规的最佳方法

我在c#中有一个插入表中的循环。 很基本的东西。 当违反了一个唯一约束时,有什么内容可以引发exception对象,我可以使用它来查看有问题的值是什么吗?

或者有没有办法在sql中返回它? 我有一系列文件,其数据加载到表格中,我正在试图找到这个骗局。

我知道我可以把一些纯粹基于IO的东西拼凑在可以找到它的代码中但是我想要一些我可以用作更永久的解决方案的东西。

您正在寻找的是SqlException,特别是违反主键约束。 通过查看抛出的exception的number属性,可以从此exception中获取此特定错误。 这个答案可能与您需要的内容相关: 如何从SQL Server 2008错误代码中识别主键重复?

总之,它看起来像这样:

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

编辑:

这可能有点hacky,但您也可以只检查exception的消息组件。 像这样的东西:

 if (ex.Message.Contains("UniqueConstraint")) // do stuff 

您可以将插入包装到存储过程中,该存储过程在插入之前首先validation没有重复项。 这样,您可以精确控制值重复时返回的内容。

此外,您可能会发现将插入逻辑转换为SP将允许您执行您似乎正在执行的批量插入,而无需重复调用数据库。

要回答您的实际问题:

SQL Server中的唯一密钥冲突 – 假设错误2627是否安全?

你也可以这样做:

 var result = DbCon.CheckForPrimaryKey(value).ToList(); if(result.Count() == 0) DbCon.InsertValue(value); else // Do Nothing 

除了Bill Sambrone的回答,

两个错误代码用于检查唯一密钥违规

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

您可以根据自己的需要使用其中一种或两种:

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

要么

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