SQL:where子句中的Switch / Case

时间:2016-08-08 07:15:01

标签: sql db2

我试图在SQL中执行此操作:

 where (table1.col1 = table1.col2 
   and  table2.col1 in ('01','02')) or
       (table1.col1 <> table1.col2 
   and  table2.col1 in ('03','04'))

我想知道如何做Switch/Case,我想尝试(但失败了):

where table2.col1 in case 
        when table1.col1 = table1.col2 then 
          ('01','02') 
        else 
          ('03','04') 
      end

2 个答案:

答案 0 :(得分:0)

您要做的是根据将执行的SQL查询部分指定条件。

使用开关/案例,您可以指定条件并根据条件,&#34;然后&#34;部分将执行一些操作。

您要做的是:&#34;然后(&#39; 01&#39;,&#39; 02&#39;)&#34;对SQL没有任何意义。在这部分中,您必须指定要执行的操作/查询。

答案 1 :(得分:0)

作为 CASE 表达式 的效果,在OP中显示的尝试是不正确的用法。 CASE表达式影响结果表达式,其中(&#39; 01&#39;&#39; 02&#39;)不是能够被评估的表达式。但是 values-clause 将是有效的结果

我在其上测试了以下WHERE子句的DB2变体给出了一个错误[sqlcode:-811&#34;结果多行&#34;]我没想到;即对于IN谓词,应该可以接受多于一行。当在DB2的某个其他variant \ level上使用时,这个编码可能是有效的和有效的吗?:

 where table2.col1 IN (case when table1.col1  = table1.col2
                            then (values('01'), ('02')) end)
    or table2.col1 IN (case when table1.col1 <> table1.col2
                            then (values('03'), ('04')) end)

以下WHERE子句按预期工作;我推断的是使用CASE表达式的上述WHERE子句的有效等价物。当然,很明显,这个使用任何CASE逻辑:

 where  table2.col1 in (select c2                             
                        from (values('01'), ('02')) as s (c2) 
                        where  table1.col1  = table1.col2    )
    or  table2.col1 in (select c2                             
                        from (values('03'), ('04')) as s (c2) 
                        where  table1.col1 <> table1.col2    )

我不确定想要使用CASE表达式的目标是什么,但是FWiW,我还提供以下内容,虽然与OP中的内容几乎相同,但可能有一些值得审查。 WHERE子句使用 CASE 表达式 来执行与OP中的WHERE子句相同的逻辑;第一个IN谓词与括号中的第二个谓词进行AND运算是可选的,但是明确表示在任何OR逻辑之外的table2.col1允许的值,假设优化器更有可能更好地识别出该限制。数据:

 where  table2.col1 in ('01', '02', '03', '04')               
   and (    table1.col1 =  case when table2.col1 in ('01','02')
                                then table1.col2 end           
        or  table1.col1 <> case when table2.col1 in ('03','04')
                                then table1.col2 end           
       )                                                      
相关问题