问题描述
我在 c# 中有一个循环插入到表中.很基本的东西.当违反唯一约束时抛出的异常对象是否有一些东西可以用来查看违规值是什么?
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 can use to see what the offending value is?
或者有没有办法在sql中返回它?我有一系列文件,它们的数据正在加载到表格中,我正在努力寻找骗子.
Or is there a way to return it in the sql? i have a series of files whose data im loading into tables and i'm banding my head trying to find the dupe.
我知道我可以将一些纯粹基于 IO 的代码拼凑在一起,可以找到它,但我想要一些可以用作更永久解决方案的东西.
I know I could slap together something purely IO-based in code that can find it but I'd like something I could use as a more permanent solution.
推荐答案
你要找的是一个SqlException,特别是违反主键约束.通过查看抛出的异常的 number 属性,您可以从此异常中获取此特定错误.这个答案可能与您需要的有关:如何识别SQL Server 2008 错误代码中的主键重复?
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
}
}
这可能有点笨拙,但您也可以只检查异常的消息组件.像这样的:
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
这篇关于在插入期间在 c# 中捕获 sql 唯一约束违规的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!