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



我想在SQL中的case. when语句中显示单个条件为真时的多个语句。

,

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

谁能给我提供确切的语法吗?

如果条件很复杂,可以将其移到子查询中。这样就不必为每一列重复设置了:

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

最新更新