tags:

views:

665

answers:

3

Hi

I have a C# code which does lot of insert statements in a batch. While executing these statements, I got "String or binary data would be truncated" error and transaction roledback.

To find out the which insert statement caused this, I need to insert one by one in the SQLServer until I hit the error.

Is there clever way to findout which statement and which field caused this issue using exception handling? (SqlException)

Thanks, Venkat

+2  A: 

In general, there isn't a way to determine which particular statement caused the error. If you're running several, you could watch profiler and look at the last completed statement and see what the statement after that might be, though I have no idea if that approach is feasible for you.

In any event, one of your parameter variables (and the data inside it) is too large for the field it's trying to store data in. Check your parameter sizes against column sizes and the field(s) in question should be evident pretty quickly.

Adam Robinson
you typed more faster than i did, upvote for you!
Darren Kopp
This information was useful to me. +1 for that.
Phil
A: 

It depends on how you are making the Insert Calls. All as one call, or as individual calls within a transaction? If individual calls, then yes (as you iterate through the calls, catch the one that fails). If one large call, then no. SQL is processing the whole statement, so it's out of the hands of the code.

MasterMax1313
A: 
BEGIN TRY
    INSERT INTO YourTable (col1, col2) VALUES (@val1, @val2)
END TRY
BEGIN CATCH
    --print or insert into error log or return param or etc...
    PRINT '@val1='+ISNULL(CONVERT(varchar,@val1),'')
    PRINT '@val2='+ISNULL(CONVERT(varchar,@val2),'')
END CATCH
KM
This assumes he's using something greater than MS SQL 2000 though ;)
Nick DeVore
@Nick DeVore, the question is vague, doesn't explain the context, and leave a lot to guess at. it does ask for "exception handling".
KM
Yes, but he says SqlException, which I would assume to be System.Data.SqlClient.SqlException ;)
Adam Robinson
@Adam Robinson, but if SqlException is what he wanted, he could have looked up the syntax himself, I think the question was asked because they were looking for ideas to address the problem.
KM