17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Note the removal of the HireDate column from the UPDATE.<br />

As we discussed earlier, the RETURN will immediately exit the sproc supplying the return value provided<br />

(in this case, –1000 — the amount matching our variable). Our client application can now test the return<br />

value and match it against a known list of possible errors.<br />

That moves us on to our second potential error. We have a couple of ways we can handle this. We could<br />

pre-query the EmployeePayHistory table to see if it already has a matching row, and then avoid the<br />

INSERT entirely. Alternatively, we can just allow <strong>SQL</strong> <strong>Server</strong> to detect the error and just beef up the error<br />

handler to address that known possibility. In this case, I’m going to opt for the latter. It is almost always<br />

better to treat the rule and handle the exception. We would like to think that this particular error is going<br />

to be very infrequent, so we’ll largely assume it isn’t going to happen and address it when it does. With<br />

this in mind, we only need to make some alterations to our error handler:<br />

…<br />

…<br />

BEGIN CATCH<br />

-- Rollback any active or uncommittable transactions before<br />

-- inserting information in the ErrorLog<br />

IF @@TRANCOUNT > 0<br />

BEGIN<br />

ROLLBACK TRANSACTION;<br />

END<br />

EXECUTE dbo.uspLogError;<br />

IF ERROR_NUMBER() = 2627 -- Primary Key violation<br />

BEGIN<br />

PRINT ‘Duplicate Rate Change Found’;<br />

RETURN @DUPLICATE_RATE_CHANGE;<br />

END<br />

END CATCH;<br />

…<br />

…<br />

Chapter 12: Stored Procedures<br />

OK, so with all these changes in place, let’s take a look at our new overall sproc. While this is a new<br />

sproc, I’m highlighting only those lines that change versus the original we cloned it from:<br />

CREATE PROCEDURE HumanResources.uspEmployeeHireInfo2<br />

@BusinessEntityID [int],<br />

@JobTitle [nvarchar](50),<br />

@HireDate [datetime],<br />

@RateChangeDate [datetime],<br />

@Rate [money],<br />

@PayFrequency [tinyint],<br />

@CurrentFlag [dbo].[Flag]<br />

WITH EXECUTE AS CALLER<br />

AS<br />

BEGIN<br />

SET NOCOUNT ON;<br />

387

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!