Search code examples
sqlsql-serverisnulldivide-by-zero

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?


Solution

  • SET @SomeVariable = @AnotherVariable / COALESCE(
            CASE 
                 WHEN @VariableEqualToZero = 0 THEN 1
                 ELSE @VariableEqualToZero
            END, 1) - 1