当一个条件为真时,我可以执行多个表达式,例如SQL中的语句吗?

时间:2013-01-11 08:21:14

标签: mysql sql cognos cognos-8

我希望在单个条件为真时显示多个语句,例如SQL中的语句。

例如:

case when (condition is true) then 
print "A" 
print "B"
.
.
.
.
print "Z"
when (condition2 is true) then 
print "Z" 
print "Y"
.
.
.
.
print "A

end

有人能为我提供确切的语法吗? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

如果您的情况很复杂,可以将其移至子查询。这样你就不必为每一列重复它了:

select  case when Condition = 1 then 'A' else 'B' end
,       case when Condition = 1 then 'C' else 'D' end
,       case when Condition = 1 then 'E' else 'F' end
,       ...
from    (
        select  *
        ,       case
                when ... complex condition ... then 1 
                else 0 
                end as Condition
        from    YourTable
        ) as SubQueryAlias

另一种选择是与CTE的联合(在所有数据库中都不可用。)这允许您在没有case的情况下为两者写入表达式,并且由于CTE,条件不会重复。

;       with CteAlias as
        (
        select  *
        ,       case
                when ... complex condition ... then 1 
                else 0 
                end as Condition
        from    YourTable
        )
select  'A', 'C', 'E'
from    CteAlias
where   Condition = 1
union all
select  'B', 'D', 'F'
from    CteAlias
where   Condition = 0