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 ='和案件中的空。任何人都可以更正查询吗?
答案 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
。