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.

in your relational database. These new features are somewhat advanced and take quite a bit of effort to<br />

master, so I am going to defer drilling into these topics. We’re going to consider them to be out of the<br />

scope of this book — see the Advanced Data Structures chapter in Professional level title for more information<br />

on the new HierarchyID data type.<br />

If you would like to see examples of the new hierarchical functionality that is part of <strong>SQL</strong><br />

<strong>Server</strong> <strong>2008</strong>, check out the OrganizationNode and OrganizationLevel columns of the<br />

HumanResources.Employee table in AdventureWorks<strong>2008</strong>.<br />

To continue our discussion of hierarchical data, we are going to handle hierarchies the way we’ve been<br />

forced to for ages — call it the “old school method.” Since AdventureWorks<strong>2008</strong> doesn't have an a good<br />

example of this older (and still far more prevalent) way of doing hierarchical data, we'll create our own<br />

version of the Employee table (we'll call it Employee2) that implements this “old school method” of<br />

addressing hierarchies. If you ran the BuildAndPopulateEmployee2.sql file back in Chapter 3, then<br />

you already have this new version of Employee. If you didn't, go ahead and execute it now (again, it is<br />

available on the wrox.com or professionalsql.com websites).<br />

The table created by this script is represented in Figure 13-1.<br />

Figure 13-1<br />

Assuming you've executed the script and have the Employee2 table, let's see if we can retrieve a list of<br />

reports for Karla Huntington.<br />

At first glance, this seems pretty easy. If we wanted to know all the people who report to Karla, we<br />

might write a query that would join the Employee table back to itself — something like:<br />

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

SELECT<br />

FROM<br />

TheReport.EmployeeID,<br />

TheReport.JobTitle,<br />

TheReport.LastName,<br />

TheReport.FirstName<br />

Chapter 13: User-Defined Functions<br />

HumanResources.Employee2 as TheBoss<br />

JOIN HumanResources.Employee2 AS TheReport<br />

ON TheBoss.EmployeeID = TheReport.ManagerID<br />

WHERE TheBoss.LastName = ‘Huntington’ AND TheBoss.FirstName = ‘Karla’;<br />

419

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

Saved successfully!

Ooh no, something went wrong!