Problem: With SQL server you have a computed column that has the following formula: SomeColumnA / SomeColumnB, where SomeColumnA and SomeColumnB are non-NULL numeric columns. Clearly a problem can arise if there is a record in the database with SomeColumnB equal to 0.0, as that will result in a Divide by zero error. Assume that the business requirements require that SomeColumnB might, indeed, be 0.0 for some records, and for such records, the computed column should result in a value of 0.0. The problem - how do you do this, as computed columns don't allow conditional statements.
My Solution: Here's my solution (feel free to nitpick, suggest alternative approaches, lambast it as causing more detriment to the field of computer science than GOTOs, etc.). For the computed column's formula I used NULLIF to see if SomeColumnB was 0.0. If so, I have it return NULL, and the division will result in NULL. I then wrapped the whole thing in an ISNULL, so if the division resulted in NULL, the result was 0.0:
ISNULL(SomeColumnA / NULLIF(SomeColumnB, 0.0), 0.0)
I'm hardly a SQL buff, so if there are any pitfalls to this approach, share them in the blog's comments, please. On a closing note, let me quote from Sql-Server-Performance.com's comments on computed columns:
Generally, using computed columns in a table is not recommended because it does not follow the standard rules of normalization. But, it is sometimes more efficient overall if you use computed columns in a table than having to recompute the same data over and over in queries. [Empahsis their's.] This is especially true if you are running the same query over and over against your data that performs the same calculations over and over. By performing the calculations in the table, it can reduce the amount of work performed by a query each time it is run. You have to determine for yourself where the bottleneck in performance is, and act accordingly. If the bottleneck is in INSERTS and UPDATES, then using calculated columns may not be a good idea. But if your SELECT statements are the bottleneck, then using calculated columns may pay off.
UPDATE (Oct. 19th, 2004 - 1:05 PM PST): A helpful post from graz in the comments indicated that CASE statements can be used in a computed column, thereby providing conditional-like semantics for a computed column. To learn more about CASE be sure to check out graz's article The case for CASE.