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.

Chapter 7: Adding More to Our Queries<br />

As you can see, we were able to take a seemingly impossible query and make it both possible and even<br />

reasonably well performing.<br />

Keep in mind that derived tables aren’t the solutions for everything. For example, if the result set is<br />

going to be fairly large and you’re going to have lots of joined records, then you may want to look at<br />

using a temporary table and building an index on it (derived tables have no indexes). Every situation is<br />

different, but now you have one more weapon in your arsenal.<br />

The EXISTS Operator<br />

200<br />

I call EXISTS an operator, but Books Online calls it a keyword. That’s probably because it defies<br />

description in some senses. It’s an operator much like the IN keyword is, but it also looks at things just<br />

a bit differently.<br />

When you use EXISTS, you don’t really return data — instead, you return a simple TRUE/FALSE regarding<br />

the existence of data that meets the criteria established in the query that the EXISTS statement is<br />

operating against.<br />

Let’s go right to an example, so you can see how this gets applied. What we’re going to query here is a<br />

list of persons who are employees:<br />

SELECT BusinessEntityID, LastName + ', ' + FirstName AS Name<br />

FROM Person.Person pp<br />

WHERE EXISTS<br />

(SELECT BusinessEntityID<br />

FROM HumanResources.Employee hre<br />

WHERE hre.BusinessEntityID = pp.BusinessEntityID);<br />

As we might expect, this gets us a relatively small subset of our Person table — 290 of them:<br />

BusinessEntityID Name<br />

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

263 Trenary, Jean<br />

78 D'sa, Reuben<br />

242 Poe, Deborah<br />

…<br />

…<br />

95 Scardelis, Jim<br />

215 Harrington, Mark<br />

112 Evans, John<br />

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

We could have easily done this same thing with a join:<br />

SELECT pp.BusinessEntityID, LastName + ', ' + FirstName AS Name<br />

FROM Person.Person pp<br />

JOIN HumanResources.Employee hre<br />

ON pp.BusinessEntityID = hre.BusinessEntityID;

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

Saved successfully!

Ooh no, something went wrong!