我试图根据结果数量在两个选择的staments之间进行选择。在以下case语句之外进行测试时,每个语句都返回有效数据。
SELECT CASE
WHEN Count(base.id) > 0 THEN base.id
ELSE (SELECT id
FROM tablea
WHERE pid = @val)
END
FROM (SELECT id
FROM tablea
WHERE id = @val) AS base
当base.Id> 0时,它返回正确,否则为Null,而它应该从我的表中有7行
答案 0 :(得分:4)
WHEN COUNT(base.id) >0
始终为真,因为您的FROM
会过滤掉id<> @val的行。除非我误解了你想要的东西,否则以下内容会给你带来理想的结果:
SELECT id
FROM tablea
WHERE id = @val OR pid = @val
更新:
SELECT id
FROM tablea
WHERE id = @val OR (pid = @val
AND NOT EXISTS (SELECT NULL FROM tablea WHERE id = @val))
答案 1 :(得分:1)
听起来你想要选择一组行,否则就会选择第二组。一种方法是union
两组,然后选择你想要的东西:
select id from (
select id, 1 as Selector
from tablea
where id = @val
union
select id, 2
from tablea
where pid = @val ) as Placeholder
where Selector = case when exists ( select 42 from tablea where id = @val ) then 1 else 2 end
我假设id
不可为空。