Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Check for IsNull and for Zero

I have the following:

set @SomeVariable = @AnotherVariable/isnull(@VariableEqualToZero,1) - 1 

If @VariableEqualToZero is null it substitutes the 1. I need it to substitute 1 if @VariableEqualToZero = 0 as well. How do I do this?

like image 675
Jeff Avatar asked Feb 24 '09 03:02

Jeff


2 Answers

If you're using SQL Server, you can probably use a NULLIF statement?
i.e. set the value to NULL if it's 0 then set it to 1 if it's NULL - should catch for both 0's and NULLs:

SET @SomeVariable = @AnotherVariable/ISNULL(NULLIF(@VariableEqualToZero,0),1) - 1
like image 129
Orion Leung Avatar answered Sep 30 '22 23:09

Orion Leung


SET @SomeVariable = @AnotherVariable / COALESCE(
        CASE 
             WHEN @VariableEqualToZero = 0 THEN 1
             ELSE @VariableEqualToZero
        END, 1) - 1
like image 36
user53794 Avatar answered Sep 30 '22 23:09

user53794