Hi,
What can be done to handle errors in stored procedure?
Thanks
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Andrew FensterPosted Apr 11, 2011, 12:59 PM
I prefer not to have the database handle the error. I would rather have the call to the database throw an exception and then catch the exception in the code and handle it there. There are several reasons:
(1) You still have to wrap your database call in a try/catch block. After all, the database might be down, the connection string might be invalid, etc. So you're going to be writing code to handle errors anyhow.
(2) If you catch the error in your code, you can handle it the same way you handle other types of exceptions.
(3) If you catch the error in your code, you can change databases without changing your error handling.
Savita JoshiPosted Apr 12, 2011, 9:28 PM
Thanks a lot for answering.
Andrew FensterPosted Apr 12, 2011, 8:58 AM
Declare @ErrorCode int
Select @ErrorCode = @@Error
If @ErrorCode = 0
Begin
--Some statement
[Update something here.]
Select @ErrorCode = @@Error
End
If @ErrorCode = 0
Begin
--Another statement
[Insert something here.]
Select @ErrorCode = @@Error
End
Return @ErrorCode
This uses the built in @@Error object. If everything succeeded, @@Error should be 0. The code that calls the stored procedure will check the return code to make sure it's 0.
A good article: http://msdn.microsoft.com/en-us/library/aa175920%28v=sql.80%29.aspx
Savita JoshiPosted Apr 11, 2011, 9:53 PM
Thanks for replying. You spoke about handling errors inside stored procedure, how do you do that please tell me.In case using SQL 2005