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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 12: Stored Procedures<br />

Dropping Sprocs<br />

It doesn’t get much easier than this:<br />

DROP PROC|PROCEDURE [;]<br />

And it’s gone.<br />

Parameterization<br />

A stored procedure gives you some (or in the case of .NET, a lot of) procedural capability and also gives you<br />

a performance boost (more on that later), but it wouldn’t be much help in most circumstances if it couldn’t<br />

accept some data to tell it what to do. For example, it doesn’t do much good to have a spDeleteVendor<br />

stored procedure if we can’t tell it what vendor we want to delete, so we use an input parameter. Likewise,<br />

we often want to get information back out of the sproc — not just one or more recordsets of table data,<br />

but also information that is more direct. An example here might be where we update several records in a<br />

table and we’d like to know just how many we updated. Often, this isn’t easily handed back in recordset<br />

form, so we make use of an output parameter.<br />

From outside the sproc, parameters can be passed in either by position or by reference. From the inside,<br />

it doesn’t matter which way they come in — they are declared the same either way.<br />

Declaring Parameters<br />

370<br />

Declaring a parameter requires two to four of these pieces of information:<br />

❑ The name<br />

❑ The data type<br />

❑ The default value<br />

❑ The direction<br />

The syntax is:<br />

@parameter_name [AS] datatype [= default|NULL] [VARYING] [OUTPUT|OUT]<br />

The name has a pretty simple set of rules to it. First, it must start with the @ sign (just like variables do).<br />

Other than that, the rules for naming are pretty much the same as the rules for naming described in<br />

Chapter 1, except that they cannot have embedded spaces.<br />

The data type, much like the name, must be declared just as you would for a variable — with a valid<br />

<strong>SQL</strong> <strong>Server</strong> built-in or user-defined data type.<br />

One special thing in declaring the data type is to remember that, when declaring a parameter of type<br />

CURSOR, you must also use the VARYING and OUTPUT options. The use of this type of parameter is<br />

pretty unusual and well outside the scope of this book, but keep it in mind in case you see it in books<br />

online or other documentation and wonder what that’s all about.<br />

Note also that OUTPUT can be abbreviated to OUT.

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

Saved successfully!

Ooh no, something went wrong!