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.

CREATE PROC spTestReturns<br />

AS<br />

DECLARE @MyMessage varchar(50);<br />

DECLARE @MyOtherMessage varchar(50);<br />

SELECT @MyMessage = ‘Hi, it’’s that line before the RETURN’;<br />

PRINT @MyMessage;<br />

RETURN;<br />

SELECT @MyOtherMessage = ‘Sorry, but we won’’t get this far’;<br />

PRINT @MyOtherMessage;<br />

RETURN;<br />

Note that I didn't choose to initialize the two message variables in the declaration this time. Why? Well,<br />

in this case, I believe it makes for substantiallly more readable code if I keep the initialization on it's own<br />

line — this is going to be true with most any string variable where the initial value is more than a few<br />

characters long.<br />

OK, now we have a sproc, but we need a small script to test out a couple of things for us. What we want<br />

to see is:<br />

❑ What gets printed out<br />

❑ What value the RETURN statement returns<br />

To capture the value of a RETURN statement, we need to assign it to a variable during our EXEC statement.<br />

For example, the following code would assign whatever the return value is to @ReturnVal:<br />

EXEC @ReturnVal = spMySproc;<br />

Now let’s put this into a more useful script to test out our sproc:<br />

DECLARE @Return int;<br />

EXEC @Return = spTestReturns;<br />

SELECT @Return;<br />

Short but sweet — when we run it, we see that the RETURN statement did indeed terminate the code<br />

before anything else could run:<br />

Hi, it’s that line before the RETURN<br />

-----------<br />

0<br />

(1 row(s) affected)<br />

Chapter 12: Stored Procedures<br />

We also got back the return value for our sproc, which was zero. Notice that the value was zero even<br />

though we didn’t specify a specific return value. That’s because the default is always zero.<br />

Think about this for a minute — if the return value is zero by default, then that means that the default<br />

return is also, in effect, “No Errors.” This has some serious dangers to it. The key point here is to make<br />

sure that you always explicitly define your return values — that way, you are reasonably certain to be<br />

returning the value you intended, rather than something by accident.<br />

377

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

Saved successfully!

Ooh no, something went wrong!