我的要求:如果'name'和'address'不为null,那么请考虑两者的值。如果其中一个为空,但是给出了其他的,只需“搜索”给定的。
SELECT * from myTable where (1=1) AND (@p_ID is null or [Id] = @p_ID)
AND
case
when [Name] IN (SELECT keyValue FROM @p_PersonalData)
then
((SELECT COUNT(*) AS lines FROM @p_PersonalData) = 0
OR ([Address] IN (SELECT dictKey FROM @p_PersonalData))
AND ([Name] IN (SELECT keyValue FROM p_PersonalData)))
else
((SELECT COUNT(*) AS lines FROM @p_PersonalData) = 0
OR ([Address] IN (SELECT dictKey FROM p_PersonalData))
ORDER BY [...]
info:没有案例,它完美无缺。选择语句和和/或完全没问题
问题是,sql server管理工作室在'= 0'处强调等号,并表示他期望AND或THEN,但是有一个'那么'......
答案 0 :(得分:1)
你有"然后/其他"块。这样的事情:
else
((SELECT COUNT(*) AS lines FROM @p_PersonalData) = 0
OR ([Address] IN (SELECT dictKey FROM p_PersonalData))
是无效的语法。
试试这个。请注意,WHERE子句中的情况可能非常低效,您应该考虑以更实质的方式重构此查询。但这应该让你开始:
SELECT *
from myTable
where (1=1)
AND (@p_ID is null or [Id] = @p_ID)
AND case when [Name] IN (SELECT keyValue FROM @p_PersonalData)
then case when (
(SELECT COUNT(*) AS lines FROM @p_PersonalData) = 0
OR
([Address] IN (SELECT dictKey FROM @p_PersonalData))
AND
([Name] IN (SELECT keyValue FROM p_PersonalData))
)
then 1
else 0
end
else case when (
(SELECT COUNT(*) AS lines FROM @p_PersonalData) = 0 OR ([Address] IN (SELECT dictKey FROM p_PersonalData)
)
then 1
else 0
end
end = 1
ORDER BY [...]