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.

Chapter 12: Stored Procedures<br />

386<br />

returning numbers and, instead, return a variable name that will make my code more readable by indicating<br />

the nature of the error I’m returning.<br />

…<br />

…<br />

SET NOCOUNT ON;<br />

-- Set up “constants” for error codes<br />

DECLARE @BUSINESS_ENTITY_ID_NOT_FOUND int,<br />

@DUPLICATE_RATE_CHANGE int<br />

SET @BUSINESS_ENTITY_ID_NOT_FOUND = -1000<br />

SET @DUPLICATE_RATE_CHANGE = -2000<br />

BEGIN TRY<br />

…<br />

…<br />

You may be curious as to why I’m using negative values here for my errors. While there is no real<br />

standard on such things, I tend to use positive values for return codes that are informational in nature<br />

(perhaps there are multiple possible successful outcomes and I want to indicate which successful outcome<br />

occurred) and negative values for errors. You can find your own path on such things; just make sure you<br />

follow the cardinal rule — be consistent! Also, I am deliberately not using the initialization syntax that<br />

became available in <strong>SQL</strong> <strong>Server</strong> <strong>2008</strong> (I would change the declare to DECLARE @BUSINESS_ENTITY_<br />

ID_NOT_FOUND int = -1000). This is purely for backward compatibility reasons, so adjust accordingly.<br />

Next, we can test how many rows were affected by the UPDATE to HumanResources.Employee and utilize<br />

that to detect a BusinessEntityID Not Found error:<br />

…<br />

…<br />

UPDATE HumanResources.Employee<br />

SET JobTitle = @JobTitle,<br />

HireDate = @HireDate,<br />

CurrentFlag = @CurrentFlag<br />

WHERE BusinessEntityID = @BusinessEntityID;<br />

IF @@ROWCOUNT > 0<br />

-- things happened as expected<br />

INSERT INTO HumanResources.EmployeePayHistory<br />

(BusinessEntityID,<br />

RateChangeDate,<br />

Rate,<br />

PayFrequency)<br />

VALUES (@BusinessEntityID, @RateChangeDate, @Rate, @PayFrequency);<br />

ELSE<br />

-- ruh roh, the update didn’t happen, so skip the insert,<br />

-- set the return value and exit<br />

BEGIN<br />

PRINT ‘BusinessEntityID Not Found’;<br />

ROLLBACK TRAN;<br />

RETURN @BUSINESS_ENTITY_ID_NOT_FOUND;<br />

END<br />

…<br />

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

Saved successfully!

Ooh no, something went wrong!