[英]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.如果@VariableEqualToZero 是null,它会替换1。如果@VariableEqualToZero = 0,我也需要它替换1。 How do I do this?
我该怎么做呢?
If you're using SQL Server, you can probably use a NULLIF
statement?如果您使用的是 SQL 服务器,您可能可以使用
NULLIF
语句?
ie 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:即将值设置为
NULL
如果它是0
然后将它设置为1
如果它是NULL
- 应该捕获 0 和 NULL:
SET @SomeVariable = @AnotherVariable/ISNULL(NULLIF(@VariableEqualToZero,0),1) - 1
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你用 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. COALESCE 和 ISNULL 本质上只是 CASE 语句的快捷方式。 You can consult the help for the syntax of CASE.
您可以查阅 CASE 语法的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.