Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 When To Use Try/Catch

Author  Topic 

dohamsg
Starting Member

22 Posts

Posted - 2008-09-23 : 12:13:38
Should I use Try/Catch block each time I Insert, Update or delete from a table?

I mean if in a stored procedure I checked that all the mandatory data is inputted, no duplicate found. Should I assume that the insert will success, or shall I put a Try/Catch block to catch any possible error ?

I mean I want to know the gereral practice.

Many Thanks.

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2008-09-23 : 12:27:02
In general I would say that you should wrap just about everything in a Try/Catch block. So, you sould wrap everything, including your validation code. Here is a quick example:
CREATE PROCEDURE dbo.MySproc(@MyDate DATETIME)
AS
SET NOCOUNT ON

BEGIN TRY

-- Validation
IF (@MyDate IS NULL)
BEGIN
RAISERROR(N'Parameter "@NotificationEventUID" cannot be NULL.', 16, 1, OBJECT_NAME(@@PROCID))
END


INSERT MyTable (MyDate) VALUES (@MyDate)

END TRY
BEGIN CATCH

-- Handle error

END CATCH
Go to Top of Page
   

- Advertisement -