August 26, 2004 at 5:46 pm
Hi,
I need some help with Error handling in Stored Procedures
I am calling a Stored Procedure (eg. SP_A) from another Stored Procedure (eg SP_B). I have the following code in SP B
BEGIN TRANSACTION
EXEC SP_A
IF @@ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
END
ELSE
BEGIN
COMMIT TRANSACTION
END
I was hoping, that I will be able to get around having to put Error Check statements after each line of code. But, its not working. Even though there are errors being raised in SP_A. Its not being caught in the check immediately after executing the procedure. Any ideas??
Is there any other way in SQL Server 2000 to get around the problem of checking for errors after each statement
Please advice,
Abhinav
August 26, 2004 at 11:36 pm
Abhinav,
Until we have Try/Catch blocks in T-SQL you do have to trap for errors after every proc call. It is possible to do this in a more generic fasion by creating an error handler using a label and GOTO statements.
You should also always capture the return code value from any procedure call to ensure that the result code is a zero (success). That is the best way to know that the call succeeded.
Here is a quick example of how you can build an error handler in T-SQL and keep the amount of in-line checking code to a minimum.
procedure adm_updateSomeTable
int
,@p_SomeRow Varchar(30)
nocount on
@w_error int
,@w_rowcount int
,@w_trancount int
,@w_retval int
@w_retval = 0
@w_trancount = @@trancount
TRAN updt_table
Update sometable set somerow = @p_SomeRow
where pkid = @p_PKID
select @w_error = @@error, @w_rowcount = @@rowcount
IF @w_error <> 0 or @w_rowcount = 0 goto ERROR_HANDLER
exec @w_retval = adm_updatesomething @p_PKID ,@p_SomeRow
if @w_retval <> 0 goto ERROR_HANDLER
TRAN updt_table
0
@w_trancount > @@trancount
rollback tran updt_table
@w_retval <> 0
RAISERROR('ERROR %d UPDATING TABLE test',16,1,@w_error)
RETURN @w_error
Kindest Regards,
Clayton
Viewing 2 posts - 1 through 1 (of 1 total)
You must be logged in to reply to this topic. Login to reply