PL / SQL ...如果在select中?

时间:2009-11-26 22:19:35

标签: sql database oracle plsql

在PL / SQL方面我很新,我必须修改别人的存储过程。

是否可以在select中间添加if语句?我尝试打开一个游标并从不同的表中选择一堆东西(不要问我为什么他们没有使用连接)并返回光标。我正在尝试做的事情是,有两列具有相似的数据,可以永远不会同时填充。因此,如果一个为null,则另一个应该有一个值,并且游标需要来自任何填充的值。那么...如果声明在select?

我不会发布实际代码,因为它会让你的眼球流血,但它看起来像......

open rc for
select l.data1 as ld1, l.data2 as ld2, b.data1 as bd1, 
       b.data2 as bd2, c.data1 as as c_d1, c.data2 as cd2
from tablel l, tableb b, tablec c
where blahblahblah
and c.data1 = [b.data3 if b.data4 is null, else b.data4]?

如果可能的话,我似乎无法获得语法。

5 个答案:

答案 0 :(得分:8)

您可以使用NVL或COALESCE:

open rc for
select l.data1 as ld1, l.data2 as ld2, b.data1 as bd1,
       b.data2 as bd2, c.data1 as as c_d1, c.data2 as cd2
from tablel l, tableb b, tablec c
where blahblahblah
and c.data1 = coalesce(b.data4,b.data3)

答案 1 :(得分:5)

改为使用案例陈述?

and c.data1 = CASE WHEN b.data3 IS NOT NULL THEN b.data3 ELSE b.data4 END

答案 2 :(得分:3)

使用decodecase,具体取决于您的Oracle版本。

例如:

and c.data1 = case bdata4 when null then bdata3 else bdata4 end

Decode类似,但用例除非您被迫使用decode,因为它更容易阅读。

Examples

答案 3 :(得分:1)

您不需要IF,可以使用OR进行此操作。

SELECT
    l.data1 AS ld1, 
    l.data2 AS ld2, 
    b.data1 AS bd1, 
    b.data2 AS bd2, 
    c.data1 AS c_d1, 
    c.data2 AS cd2
FROM
    tablel l, 
    tableb b,
    tablec c
WHERE
    ... blahblahblah ...
AND (
      ( b.data4 IS NULL AND c.data1 = b.data3 ) OR ( c.data1 = b.data4 )
    )

答案 4 :(得分:0)

听起来你在选择部分需要一个案例陈述?