SQL Server Check for IsNull and for Zero

2019-03-25 05:56发布

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?

4条回答
再贱就再见
2楼-- · 2019-03-25 06:06
set @SomeVariable = @AnotherVariable /
(case when isnull(@VariableEqualToZero, 0) = 0 then 1 else
@VariableEqualToZero end) - 1
查看更多
再贱就再见
3楼-- · 2019-03-25 06:14

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
查看更多
该账号已被封号
4楼-- · 2019-03-25 06:15
SET @SomeVariable = @AnotherVariable / COALESCE(
        CASE 
             WHEN @VariableEqualToZero = 0 THEN 1
             ELSE @VariableEqualToZero
        END, 1) - 1
查看更多
Juvenile、少年°
5楼-- · 2019-03-25 06:29

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.

查看更多
登录 后发表回答