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.

The default is the first place we start to see any real divergence from variables. Where variables are<br />

always initialized to a NULL value, parameters are not. Indeed, if you don’t supply a default value, then<br />

the parameter is assumed to be required, and a beginning value must be supplied when the sproc is<br />

called.<br />

So, for example, let’s try a slightly different version of our previous sproc. This time, we’ll be supplying<br />

name information from the Person.Person table and accepting a filter for the last name:<br />

USE AdventureWorks<strong>2008</strong>;<br />

GO<br />

CREATE PROC spEmployeeByName<br />

@LastName nvarchar(50)<br />

AS<br />

SELECT p.LastName, p.FirstName, e.JobTitle, e.HireDate<br />

FROM Person.Person p<br />

JOIN HumanResources.Employee e<br />

ON p. BusinessEntityID = e.BusinessEntityID<br />

WHERE p.LastName LIKE @LastName + ‘%’;<br />

Try this sproc supplying the required default:<br />

EXEC spEmployeeByName ‘Dobney’;<br />

And you get a very short list back (indeed, just one employee):<br />

LastName FirstName JobTitle HireDate<br />

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

Dobney JoLynn Production Supervisor - WC60 1998-01-26<br />

Be careful using wildcard matches, such as the LIKE statement used in the preceding<br />

code. This particular example would likely perform OK because the wildcard is at the<br />

end. Keep in mind that wildcards used at the beginning of a search effectively eliminate<br />

the opportunity for <strong>SQL</strong> <strong>Server</strong> to use an index since any starting character is<br />

potentially a match.<br />

Now check what happens if we don’t supply the default:<br />

EXEC spEmployeeByName;<br />

<strong>SQL</strong> <strong>Server</strong> wastes no time in informing us of the error of our ways:<br />

Msg 201, Level 16, State 4, Procedure spEmployeeByName, Line 0<br />

Procedure or Function ‘spEmployeeByName’ expects parameter ‘@LastName’, which was<br />

not supplied.<br />

Because no default was provided, the parameter is assumed to be required.<br />

Chapter 12: Stored Procedures<br />

371

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

Saved successfully!

Ooh no, something went wrong!