简体   繁体   English

在SQL中出现大小写为空的问题

[英]Issue with case null in sql

SELECT Id 
FROM dbo.OWL_AddlDataFields 
WHERE CustomerId = @BaseCustomerId 
  AND AddlDataFieldCategoryId = @AddlDataFieldCategoryId 
  AND AddlDataFieldGroupId = CASE 
                                WHEN @AddlDataFieldGroupId =  0 THEN  NULL 
                                ELSE  @AddlDataFieldGroupId 
                             END  
  AND Name = @DataFieldName

The above query does not returns any result. 上面的查询不返回任何结果。 I think above query has issue with the 'AddlDataFieldCategoryId =' and the null from the case. 我认为上面的查询存在'AddlDataFieldCategoryId ='和案例中的null的问题。 Can anybody correct the query? 有人可以更正查询吗?

The issue with your CASE expression is that you are comparing a column to a predicate which might be NULL using the equals operator. CASE表达式的问题在于,您正在使用equals运算符将一列与可能为NULL的谓词进行比较。 This won't behave as expected, because NULL comparisons should use IS NULL instead of equals. 这不会达到预期的效果,因为NULL比较应该使用IS NULL而不是equals。 One possible workaround would be to coalesce AddlDataFieldGroupId to a numeric value. 一种可能的解决方法是将AddlDataFieldGroupId合并为一个数值。 Then, we can be certain that the CASE expression would only be comparing one number to another. 然后,我们可以确定CASE表达式只会将一个数字与另一个数字进行比较。

WHERE ... AND
COALESCE(AddlDataFieldGroupId, 0) = CASE WHEN 
                    @AddlDataFieldGroupId =  0
                                         THEN 0 ELSE  @AddlDataFieldGroupId END

If your AddlDataFieldGroupId cannot be zero, then you don't need the CASE at all. 如果您的AddlDataFieldGroupId不能为零,则根本不需要CASE This will do the job: 这将完成工作:

SELECT Id 
FROM dbo.OWL_AddlDataFields 
WHERE CustomerId = @BaseCustomerId 
AND AddlDataFieldCategoryId = @AddlDataFieldCategoryId 
AND AddlDataFieldGroupId = @AddlDataFieldGroupId
AND Name = @DataFieldName

If AddlDataFieldGroupId can be zero, but cannot be negative, you can do this: 如果AddlDataFieldGroupId可以为零,但不能为负,则可以执行以下操作:

SELECT Id 
FROM dbo.OWL_AddlDataFields 
WHERE CustomerId = @BaseCustomerId 
AND AddlDataFieldCategoryId = @AddlDataFieldCategoryId 
AND AddlDataFieldGroupId = CASE WHEN 
@AddlDataFieldGroupId =  0 THEN -1 ELSE @AddlDataFieldGroupId END  
AND Name = @DataFieldName

Alternatively, this will work regardless of what AddlDataFieldGroupId can be: 另外,不管AddlDataFieldGroupId可以是什么,它都将起作用:

SELECT Id 
FROM dbo.OWL_AddlDataFields 
WHERE CustomerId = @BaseCustomerId 
AND AddlDataFieldCategoryId = @AddlDataFieldCategoryId 
AND AddlDataFieldGroupId = CASE WHEN 
@AddlDataFieldGroupId =  0 THEN AddlDataFieldGroupId - 1 ELSE @AddlDataFieldGroupId END  
AND Name = @DataFieldName

Note: all these solutions assume that AddlDataFieldGroupId cannot be NULL . 注意:所有这些解决方案均假定AddlDataFieldGroupId不能为NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM