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.

AS<br />

RETURN (SELECT BusinessEntityID,<br />

LastName + ‘, ‘ + FirstName AS Name<br />

FROM Person.Person);<br />

GO<br />

This function returns a table of selected records and does a little formatting — joining the last and first<br />

names, and separating them with a comma.<br />

At this point, we’re ready to use our function just as we would use a table:<br />

SELECT *<br />

FROM dbo.fnContactList();<br />

Now, let’s add a bit more fun into things. What we did with this table up to this point could have been<br />

done just as easily — more easily, in fact — with a view. But what if we wanted to parameterize a view?<br />

What if, for example, we wanted to accept last-name input to filter our results (without having to manually<br />

put in our own WHERE clause)? It might look something like this:<br />

--CREATE our view<br />

CREATE VIEW vFullContactName<br />

AS<br />

SELECT p.BusinessEntityID,<br />

LastName + ‘, ‘ + FirstName AS Name,<br />

ea.EmailAddress<br />

FROM Person.Person as p<br />

LEFT OUTER JOIN Person.EmailAddress ea<br />

ON ea.BusinessEntityID = p.BusinessEntityID;<br />

GO<br />

This would yield us what was asked for, with a twist. We can’t parameterize things right in the view<br />

itself, so we’re going to have to include a WHERE clause in our query:<br />

SELECT *<br />

FROM vFullContactName<br />

WHERE Name LIKE ‘Ad%’;<br />

This should get you results that look something like this:<br />

BusinessEntityID Name EmailAddress<br />

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

67 Adams, Jay jay0@adventure-works.com<br />

301 Adams, Frances frances0@adventure-works.com<br />

305 Adams, Carla carla0@adventure-works.com<br />

…<br />

…<br />

16901 Adams, Adam adam46@adventure-works.com<br />

16902 Adams, Eric eric57@adventure-works.com<br />

16910 Adams, Jackson jackson47@adventure-works.com<br />

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

Chapter 13: User-Defined Functions<br />

417

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

Saved successfully!

Ooh no, something went wrong!