Friday, April 8, 2011

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?

From stackoverflow
  • set @SomeVariable = @AnotherVariable / coalesce(case when @VariableEqualToZero = 0 then 1 else @VariableEqualToZero end, 1) - 1
    
  • set @SomeVariable = @AnotherVariable /
    (case when isnull(@VariableEqualToZero, 0) = 0 then 1 else
    @VariableEqualToZero end) - 1
    
  • You use CASE

    instead of

    ISNULL(@VariableEqualToZero,1)
    

    use

    CASE WHEN @VariableEqualToZero IS NULL OR @VariableEqualToZero = 0 THEN 1 ELSE @VariableEqualToZero END
    

    COALESCE and ISNULL are essentially just shortcuts for a CASE statement. You can consult the help for the syntax of CASE.

0 comments:

Post a Comment