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.

Now let’s see this at work in our query:<br />

SELECT sc.AccountNumber,<br />

ISNULL(CAST((SELECT Min(OrderDate)<br />

FROM Sales.SalesOrderHeader soh<br />

WHERE soh.CustomerID = sc.CustomerID) AS varchar), ‘NEVER ORDERED’)<br />

AS OrderDate<br />

FROM Sales.Customer sc;<br />

Now, some example lines that we had problems with. We go from:<br />

…<br />

…<br />

AW00000696 NULL<br />

AW00000697 NULL<br />

AW00000698 NULL<br />

AW00011012 2003-09-17 00:00:00.000<br />

AW00011013 2003-10-15 00:00:00.000<br />

AW00011014 2003-09-24 00:00:00.000<br />

…<br />

…<br />

to something a bit more useful:<br />

…<br />

…<br />

AW00000696 NEVER ORDERED<br />

AW00000697 NEVER ORDERED<br />

AW00000698 NEVER ORDERED<br />

AW00011012 Sep 17 2003 12:00AM<br />

AW00011013 Oct 15 2003 12:00AM<br />

AW00011014 Sep 24 2003 12:00AM<br />

…<br />

…<br />

Notice that I also had to put the CAST() function into play to get this to work. The reason has to do<br />

with casting and implicit conversion. Because the column Order Date is of type DateTime there is<br />

an error generated since NEVER ORDERED can’t be converted to the DateTime data type. Keep CAST()<br />

in mind — it can help you out of little troubles like this one. This is covered further later in this chapter.<br />

So, at this point, we’ve seen correlated subqueries that provide information for both the WHERE clause<br />

and for the select list. You can mix and match these two in the same query if you wish.<br />

Derived Tables<br />

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

Sometimes you need to work with the results of a query, but you need to work with the results of that<br />

query in a way that doesn’t really lend itself to the kinds of subqueries that we’ve discussed up to this<br />

197

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

Saved successfully!

Ooh no, something went wrong!