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 />

This returns data that looks something like this:<br />

AccountNumber OrderDate<br />

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

AW00000001 NULL<br />

AW00000002 NULL<br />

AW00000007 NULL<br />

…<br />

…<br />

AW00030102 2002-12-01 00:00:00.000<br />

AW00030104 2002-07-01 00:00:00.000<br />

AW00030113 2002-09-01 00:00:00.000<br />

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

Note that there are a couple of rows that have a NULL in the Order Date column. Why do you suppose<br />

that is? The cause is, of course, because there is no record in the Orders table that matches the then current<br />

record in the Customer table (the outer query).<br />

This brings us to a small digression to take a look at a particularly useful function for this situation —<br />

ISNULL().<br />

Dealing with NULL Data — the ISNULL Function<br />

196<br />

There are actually a few functions specifically meant to deal with NULL data, but the one of particular<br />

use to us at this point is ISNULL(). ISNULL() accepts a variable (which we’ll talk about in Chapter 11)<br />

or expression and tests it for a NULL value. If the value is indeed NULL, then the function returns some other<br />

prespecified value. If the original value is not NULL, then the original value is returned. This syntax is<br />

pretty straightforward:<br />

ISNULL(, )<br />

So, for example:<br />

ISNULL Expression Value Returned<br />

ISNULL(NULL, 5) 5<br />

ISNULL(5, 15) 5<br />

ISNULL(MyColumnName, 0) where MyColumnName IS NULL 0<br />

ISNULL(MyColumnName, 0) where MyColumnName = 3 3<br />

ISNULL(MyColumnName, 0) where MyColumnName =’Fred Farmer’ Fred Farmer

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

Saved successfully!

Ooh no, something went wrong!