T-SQL Return True / False based on Is Null

by richard on November 19th, 2008

So I’m working on a project where images are uploaded to a database table. The table has an image column, and if there is no image, then the column is just null,  but otherwise the bytes for the image are stored.

An ASPX page takes in the row id for this table via querystring and serves up the bytes from the column as an actual image.

On a separate page, I’m displaying the contents of the table in a per-record listing, if there is an image, then I display a thumbnail by calling the aforementioned aspx image page.

So my problem? If only some records have images, then how do I know when to call the aspx image page? I could do something quick like:

SELECT ItemID, ItemName, ItemDescription, ItemImage FROM Table

And then check to see if ItemImage is null. But what if it isn’t null? I can’t do anything with the bytes I have, because I have a separate page for displaying the image. So in essence, I’m calling back data (potentially large data) that I don’t need. 

So what I really want is a query that looks like:

SELECT ItemID, ItemName, ItemDescription, HasImage FROM Table

Where HasImage is a bit (true/false) column, telling me if there’s an image for this item or not. But I don’t have a column in my table called HasImage and its too much work to implement one.

So the best way to solve this?

SELECT ItemID, ItemName, ItemDescription, (CASE WHEN ItemImage IS NOT NULL THEN 1 ELSE 0 END) AS HasImage FROM Table

This now tells me if this record has an image without actually bringing back the bytes for the image.

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS