日期:2014-05-17  浏览次数:21348 次

求SQL语法:如果a表中存在b字段就取a字段,如果存在b字段就取b的值,用一条语句能实现吗?
a,b肯定会有一个,不过不知是哪一个。

------解决方案--------------------
看下面的例子,在scott.emp上进行的测试。假设emp表上有B字段,就取empno,否则取ename字段。
SQL code
select A.empno
      ,nvl(a.your_need, b.your_need) your_need
  from 
(
    select  empno
           ,cast(
                   (
                case when (select count(1) from user_tab_columns where table_name = 'EMP' and column_name = 'B') > 0 then empno
                    else null
                end
                ) 
            as varchar2(7)
            ) your_need
      from emp
)
   A,
    (
    select empno
           ,case when (select count(1) from user_tab_columns where table_name = 'EMP' and column_name = 'ENAME') > 0 then ENAME
                else null
           end your_need
      from emp
    ) B
where A.empno = B.empno