使用子查询语法的情况

时间:2014-12-01 11:31:01

标签: sql case

我需要根据输入参数
检索值 例子:
param = A,结果= AB
          param = B,结果= BA,BB

我知道我需要在陈述时使用案例,但我在实施它们时遇到了一些麻烦 任何帮助将不胜感激

参数='A'

select distinct(statut.STATUT_NAME)as statutList ,
case 'A'
when 'A' then (select distinct(STATUT_NAME) as statutAllowed  from STATUT  where STATUT_NAME = 'AB')
when 'B' then (select distinct(STATUT_NAME) as statutAllowed from STATUT where STATUT_NAME = 'BA' and STATUT_NAME = 'BB')
end
from STATUT statut;
// request should returns AB

参数='B'

select distinct(statut.STATUT_NAME)as statutList ,
case 'B'
when 'A' then (select distinct(STATUT_NAME) as statutAllowed  from STATUT where STATUT_NAME = 'AB')
when 'B' then (select distinct(STATUT_NAME) as statutAllowed from STATUT where STATUT_NAME = 'BA' and STATUT_NAME = 'BB')
end
from STATUT statut;
// request should returns BA , BB

非常感谢

3 个答案:

答案 0 :(得分:1)

你应该声明变量并在你的情况下使用它,而不是硬编码案例中的值。

declare @param char(1)

select distinct(statut.STATUT_NAME)as statutList,
case @param 
when 'A' then (select distinct(STATUT_NAME) as statutAllowed  from STATUT where STATUT_NAME = 'AB')
when 'B' then (select distinct(STATUT_NAME) as statutAllowed from STATUT where STATUT_NAME = 'BA' and STATUT_NAME = 'BB')
end
from STATUT statut;

答案 1 :(得分:1)

像这样更改Case Statement。在Case语句

中将param列提取为输入表达式
SELECT DISTINCT( statut.STATUT_NAME )AS statutList,
               CASE param
                 WHEN 'A' THEN (SELECT DISTINCT( STATUT_NAME ) AS statutAllowed
                                FROM   STATUT
                                WHERE  STATUT_NAME = 'AB')
                 WHEN 'B' THEN (SELECT DISTINCT( STATUT_NAME ) AS statutAllowed
                                FROM   STATUT
                                WHERE  STATUT_NAME = 'BA'
                                       AND STATUT_NAME = 'BB')
               END
FROM   STATUT statut; 

答案 2 :(得分:1)

我猜你想要这个:

select distinct(s.STATUT_NAME) as statutList
from STATUT s
where (@param = 'A' and s.statut_name = 'AB') or
      (@paraem = 'B' and s.statut_name in ('BA', 'BB'));

一些观察结果:

  • 您的版本中的子查询没有任何影响,因为外部select位于不同的字段上。
  • 您的版本没有提及参数名称,我刚才称之为@param
  • 您的版本中的'B'子句将始终返回0,因为where子句中包含AND,并且这两个条件不能同时为真。