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

use*_*926 18 c# sql-server ado.net

我在c#中有一个插入表中的循环.很基本的东西.是否存在一些内容,当违反了一个唯一约束时抛出的异常对象可以用来查看有问题的值是什么?

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

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

Bil*_*one 21

您正在寻找的是SqlException,特别是违反主键约束.通过查看抛出的异常的number属性,可以从此异常中获取此特定错误.这个答案可能与您需要的内容相关: 如何从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
   }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

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

if (ex.Message.Contains("UniqueConstraint")) // do stuff
Run Code Online (Sandbox Code Playgroud)

  • 还要检查`ex.Number == 2601` /sf/ask/2206104351/ (2认同)

Muh*_*qib 5

除了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
   }
}
Run Code Online (Sandbox Code Playgroud)

要么

try
{

}
catch(SqlException ex)
{
   if(ex.Number == 2601 || ex.Number == 2627)
   {
      // Violation in one on both...
   }
}
Run Code Online (Sandbox Code Playgroud)