views:

2476

answers:

3

Currently I have a large import process that I'm trying to wrap inside a transaction so if anything breaks - i could rollback. The issue I have is that when the TSQL inside the trans blows up, it won't rollback when the following SQL error occurs

Msg 8152, Level 16, State 14, Line 249
String or binary data would be truncated.
The statement has been terminated.

The below wraps this import TSQL

DECLARE @error INT
SELECT @error = 0
BEGIN TRANSACTION

--** begin import TSQL

--** end import TSQL

SELECT @error = @@error 
IF @error != 0 GOTO handle_error

COMMIT

handle_error: 
IF @error != 0 
BEGIN 
ROLLBACK 
END
+5  A: 

How about turning on xact_abort

set xact_abort on
Sung Meister
Sorry for not accepting this solution, but as I was using SQL Server 2005 I found the above to be the best approach - this will be noted though as I have some SQL 2000 only apps that could benefit! Thanks again!
Toran Billups
Thank you for the feedback. And, no, you need not worry, Toran. I wish I was the one that has suggested Josh's answer. Josh's answer surely IS a better answer.
Sung Meister
+7  A: 

If your on SQL 2005 you can try:

BEGIN TRANSACTION
BEGIN TRY
    --Run your Statements
    COMMIT TRANSACTION
END TRY
BEGIN CATCH
        ROLLBACK TRANSACTION
        DECLARE @Msg NVARCHAR(MAX)  
        SELECT @Msg=ERROR_MESSAGE() 
        RAISERROR('Error Occured: %s', 20, 101,@msg) WITH LOG
END CATCH
JoshBerke
+1 for Try/Catch: I was stuck in SQL Server 2000 solution...
Sung Meister
Yep had you not suggested it already I would have done that as my fall back answer ;-)
JoshBerke
A: 

I would also point out that if you are receiving this error often, you need to revise the size of the column you are entering data into or adjust your cleaning process to prep the data before putting it into the prod table. In SSIS, You could also have the data that deosn't meet the standard size go to a bad data table and process the rest.

HLGEM