1

I am getting dividing by 0 errors. I noticed that sometimes the field I'm dividing by is NULL.

(SUM(RentMonths * SQFT) / SUM(SQFT))

What's the proper way to handle this situation when SQFT can be null at times? I know it's probably bad data but that's besides the point; I can't fix that right now.

4

2 回答 2

5

Dividing by NULL is perfectly valid - the result is simply NULL. The problem is (as the error message states) when you try to divide by zero.

You can use NULLIF to solve this problem:

(SUM(RentMonths * SQFT) / NULLIF(SUM(SQFT), 0))

The result will be NULL if the divisor is 0 or if either operand is NULL.


As pointed out in the comments, a CASE statement could also be used:

CASE WHEN SUM(SQFT) <> 0 THEN (SUM(RentMonths * SQFT) / SUM(SQFT)) END

The advantage is that this will work in almost any database, but a disadvantage is that it repeats the expression to calculate the divisor.

于 2012-07-10T15:43:06.133 回答
0

IF 语句在这里似乎很合适,不是吗?

不知道这是否是正确的 TSQL 语法,但是:

IF @SQFT IS NOT NULL (SUM(RentMonths * SQFT) / SUM(SQFT))
于 2012-07-10T15:47:10.263 回答