0

我正在尝试根据结果数量在两个选择语句之间进行选择。在以下 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 行

4

2 回答 2

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))
于 2013-01-07T18:24:30.290 回答
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是不可为空的。

于 2013-01-07T18:29:48.810 回答