首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > oracle >

求SQL语法:如果a表中存在b字段就取a字段,如果存在b字段就取b的值,用一条语句能实现吗?该怎么解决

2012-01-19 
求SQL语法:如果a表中存在b字段就取a字段,如果存在b字段就取b的值,用一条语句能实现吗?a,b肯定会有一个,不

求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    ) Bwhere A.empno = B.empno 

热点排行