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.

Building a Nested Subquery<br />

A nested subquery is one that goes in only one direction, returning either a single value for use in the outer query,<br />

or perhaps a full list of values to be used with the IN operator. In the event you want to use an explicit =<br />

operator, then you’re going to be using a query that returns a single value — that means one column from<br />

one row. If you are expecting a list back, then you’ll need to use the IN operator with your outer query.<br />

In the loosest sense, your query syntax is going to look something like one of these two syntax templates:<br />

Or:<br />

SELECT <br />

FROM <br />

WHERE = (<br />

SELECT <br />

FROM <br />

WHERE )<br />

SELECT <br />

FROM <br />

WHERE IN (<br />

SELECT <br />

FROM <br />

[WHERE )]<br />

Obviously, the exact syntax will vary, not only because you will be substituting the select list and exact<br />

table names, but also because you may have a multitable join in either the inner or outer queries — or both.<br />

Nested Queries Using Single-Value SELECT Statements<br />

Let’s get down to the nitty-gritty with an explicit example. Let’s say, for example, that we wanted to<br />

know the ProductIDs of every item sold on the first day any product was purchased from the system.<br />

If you already know the first day that an order was placed in the system, then it’s no problem; the query<br />

would look something like this:<br />

SELECT DISTINCT sod.ProductID<br />

FROM Sales.SalesOrderHeader soh<br />

JOIN Sales.SalesOrderDetail sod<br />

ON soh.SalesOrderID = sod.SalesOrderID<br />

WHERE OrderDate = ‘07/01/2001’; --This is first OrderDate in the system<br />

This yields the correct results:<br />

ProductID<br />

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

707<br />

708<br />

709<br />

…<br />

…<br />

776<br />

777<br />

778<br />

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

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

189

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

Saved successfully!

Ooh no, something went wrong!