Question

I'm doing a simple query that uses the DateDiff function to find the number of days between the dates. However, with regards to certain instances, I'd like to populate a blank field (not a null).

Something like this is what I currently have, and it seems to work fine (but it populates a null).

 [Test (Years)] = CASE WHEN TYPE IN ('A','B') 
 THEN NULL ELSE IsNull(CONVERT(decimal(28,12),
 (DATEDIFF(d,@StartDate,ExpirationDate)))/365,0) END

Now if I try something like this... which tries to convert all TYPE A and B to populate a blank, I'll get the following error message: Error converting data type varchar to numeric.

 [Test (Years)] = CASE WHEN TYPE IN ('A','B') 
 THEN '' ELSE IsNull(CONVERT(decimal(28,12),
 (DATEDIFF(d,@StartDate,ExpirationDate)))/365,0) END

Is there a simple thing I'm missing? I've tried doing the calcualtions without converting to a decimal, but it doesn't seem to work. Any ideas? Thanks

Was it helpful?

Solution

CASE is an expression that returns exactly one value and all of the branches must yield compatible types. A string (even a blank string) is not compatible with a decimal, so you need to do something like:

CASE WHEN ... THEN '' ELSE 
  CONVERT(VARCHAR(32), COALESCE(CONVERT(DECIMAL(23,12), ... ,0)) END

Note that this hack will only work if you are presenting the data to an end user. If you are trying to store this data in a column or use it in other calculations, it too will be tripped up by the blank string. A number can't be a blank string:

DECLARE @i INT = '';
SELECT @i;

Result:

0

So, if you don't want "empty" numerics to be interpreted as 0, stop being afraid of NULL and if you are dealing with this at presentation time, have the presentation layer present a blank string instead of NULL.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top