views:

79

answers:

2

Ok, so suppose I am doing an insert or an update on a table. So in the BEGIN CATCH/END CATCH I can define a variable to ERROR_MESSAGE() and get back my error message:
Cannot insert the value NULL into column 'columnname', table 'Table'; column does not allow nulls. INSERT fails.

Is there any way I could return say the primary key of the offending record or anything to identify which row actually failed? I rollback the transaction on failure so it's not like I can look at the 'last' record to see the next one which has the problem.

+2  A: 

This isn't possible AFAIK due to the fact you're not truly working on one record at a time.

Of course for inserts there are no primary keys yet assigned. If you really need that granular level of detail the best advice I can offer is to insert/update one row at a time so you know for sure which one threw the error.

Joel Mansford
somehow I was afraid that might be the answer for no other reason that I'd hate to think i've been doing this stuff for a LONG time and never came across it...
SomeMiscGuy
A: 

Personally, I check my data for things like that before I try to do an insert. Don't swtich to working one record at a time. Instead write something that will chcek for data that is not there for required fields. If you put the information on what failed into a table variable at the time of the check, it will still be available after the rollback and then you can insert it into a permanent error table to see what records were causing the problem.

HLGEM
By the fact the poster is using TRY / CATCH in T-SQL I assume the data is already all server-side, thus inserting one row at a time I don't see as being any worse then rolling a load back later.
Joel Mansford
actually the data is being calculated, some of the calculations involving several fields. Granted I could easily wrapper everything but I was hoping more for something I could use as a diagnostic since the fields are never supposed to be NULL so it would help be validate my calculations.
SomeMiscGuy
Use of try catch doen't have anything to do with processing one vice a group of rows. It is just error handling.
HLGEM