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

Supplying Default Values<br />

372<br />

To make a parameter optional, you have to supply a default value. To do this, you just add an = together<br />

with the value you want to use for a default after the data type, but before the comma. Once you’ve done<br />

this, the users of your sproc can decide to supply no value for that parameter, or they can provide their<br />

own value.<br />

So, for example, if we wanted to allow the parameter in our previous example to be optional, we would<br />

just modify the parameter declaration to include a default:<br />

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

DROP PROC spEmployeeByName; -- Get rid of the previous version<br />

GO<br />

CREATE PROC spEmployeeByName<br />

@LastName nvarchar(50) = NULL<br />

AS<br />

IF @LastName IS NOT NULL<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 />

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

Notice how I have made use of the control of flow constructs we learned in the previous chapter on<br />

scripting to decide which is the better query to run. The differences are subtle, with only the addition of<br />

a WHERE clause really differentiating the choices.<br />

Given our new default, we can now run the sproc without a parameter:<br />

EXEC spEmployeeByName;<br />

And, as expected, we get a more full result set:<br />

LastName FirstName JobTitle HireDate<br />

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

Sánchez Ken Chief Executive Officer 1999-02-15<br />

Duffy Terri Vice President of Engineering 1998-03-03<br />

Tamburello Roberto Engineering Manager 1997-12-12<br />

…<br />

…<br />

Valdez Rachel Sales Representative 2003-07-01<br />

Pak Jae Sales Representative 2002-07-01<br />

Vakey Chudu Ranjit Sales Representative 2002-07-01<br />

(290 row(s) affected)

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

Saved successfully!

Ooh no, something went wrong!