SQL Server Check for IsNull and for Zero

前端 未结 4 1824
离开以前
离开以前 2021-02-07 18:59

I have the following:

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

If @VariableEqualToZero is null it substitutes t

相关标签:
4条回答
  • 2021-02-07 19:29
    set @SomeVariable = @AnotherVariable /
    (case when isnull(@VariableEqualToZero, 0) = 0 then 1 else
    @VariableEqualToZero end) - 1
    
    0 讨论(0)
  • 2021-02-07 19:30
    SET @SomeVariable = @AnotherVariable / COALESCE(
            CASE 
                 WHEN @VariableEqualToZero = 0 THEN 1
                 ELSE @VariableEqualToZero
            END, 1) - 1
    
    0 讨论(0)
  • 2021-02-07 19:38

    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 讨论(0)
  • 2021-02-07 19:54

    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
    
    0 讨论(0)
提交回复
热议问题