Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

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

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?

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...