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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Andrew FensterRank #983 · 2K reputationPosted Apr 11, 2011, 8:59 AM EDT
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 Joshi124 reputationPosted Apr 11, 2011, 5:53 PM EDT
Thanks for replying. You spoke about handling errors inside stored procedure, how do you do that please tell me.In case using SQL 2005
Andrew FensterRank #983 · 2K reputationPosted Apr 12, 2011, 4:58 AM EDT
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 Joshi124 reputationPosted Apr 12, 2011, 5:28 PM EDT
Thanks a lot for answering.