在sql中使用case null的问题

时间:2017-07-17 05:27:17

标签: sql sql-server

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

上述查询不会返回任何结果。我认为以上查询存在“AddlDataFieldCategoryId ='和案件中的空。任何人都可以更正查询吗?

2 个答案:

答案 0 :(得分:1)

CASE表达式的问题在于您使用equals运算符将列与谓词进行比较,该谓词可能是NULL。这不会像预期的那样表现,因为NULL比较应该使用IS NULL而不是等于。一种可能的解决方法是将AddlDataFieldGroupId合并为数值。然后,我们可以确定CASE表达式只会将一个数字与另一个数字进行比较。

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

答案 1 :(得分:1)

如果AddlDataFieldGroupId不能为零,那么您根本不需要CASE。这将完成这项工作:

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

如果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

或者,无论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

注意:所有这些解决方案均假设AddlDataFieldGroupId不能为NULL