SQL Error Handling

During the pre-SQL Server 2005 days, we had to handle errors via transactions. At times, this could prove challenging when dealing with specific errors. Some might fall through making debugging difficult.

Fortunately, the team at Microsoft copied the try/catch approach from Visual Studio to SQL Server.

Here is the deprecated approach:

BEGIN TRANSACTION

DELETE FROM tblBlah
WHERE DATESENT <= @DATE IF @@ERROR = 0 COMMIT TRANSACTION ELSE ROLLBACK TRANSACTION

Here is the current best practice:

BEGIN TRY
BEGIN TRANSACTION

DELETE FROM dbo.tblBlah
WHERE DATESENT <= @DATE COMMIT TRANSACTION END TRY BEGIN CATCH IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION

END CATCH