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 />

It worked just fine. But if we try to do this using inline error checking, we have a problem:<br />

CREATE TABLE OurIFTest(<br />

Col1 int PRIMARY KEY<br />

);<br />

IF @@ERROR != 0<br />

PRINT ‘Problems!’;<br />

ELSE<br />

PRINT ‘Everything went OK!’;<br />

Run this (you’ll need to run it twice to generate the error if the table isn’t already there) and we quickly<br />

find out that, without the TRY block, <strong>SQL</strong> <strong>Server</strong> aborts the script entirely on the particular error we’re<br />

generating here:<br />

Msg 2714, Level 16, State 6, Line 2<br />

There is already an object named ‘OurIFTest’ in the database.<br />

Notice that our PRINT statements never got a chance to execute — <strong>SQL</strong> <strong>Server</strong> had already terminated<br />

processing. With TRY/CATCH we were able to trap and handle this error, but using inline error checking,<br />

our attempts to trap an error like this fail.<br />

Handling Errors Before They Happen<br />

384<br />

Sometimes you have errors that <strong>SQL</strong> <strong>Server</strong> doesn’t really have an effective way to even know about, let<br />

alone tell you about. Other times we want to prevent the errors before they happen. These we need to<br />

check for and handle ourselves.<br />

To try this out, let’s make a new version of an existing sproc in AdventureWorks<strong>2008</strong> called HumanResources<br />

.uspUpdateEmployeeHireInfo — we’ll call ours HumanResources.uspUpdateEmployeeHireInfo2.<br />

In this, let’s address some business rules that are logical in nature, but not necessarily implemented in<br />

the database (or, in this case, even possible to handle with constraints). Let’s start by taking a look at the<br />

existing sproc:<br />

CREATE PROCEDURE HumanResources.uspUpdateEmployeeHireInfo2<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 />

BEGIN TRY<br />

BEGIN TRANSACTION;<br />

UPDATE HumanResources.Employee<br />

SET JobTitle = @JobTitle,

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

Saved successfully!

Ooh no, something went wrong!