根据特定条件显示列

时间:2016-03-04 11:59:30

标签: sql oracle11g

我想基于某些条件显示列,是否可能因为我这样做会出错。

    select (
              select column_name 
              from all_tab_cols
              where table_name='BED_2016_MAR_CIT4114A_FYP1_G_' 
                    and column_name like '%na%'
           )
    from BED_2016_MAR_CIT4114A_FYP1_G_;

2 个答案:

答案 0 :(得分:0)

SQL查询必须明确列出它正在使用的列。您可以使用动态SQL(execute immediate)执行所需操作。例如:

declare
    sql varchar2(4000);
    cols varchar2(4000);
begin
    select listagg(column_name, ',') within group (order by column_name)
    into cols
    from all_tab_cols
    where table_name = 'BED_2016_MAR_CIT4114A_FYP1_G_' and column_name like '%na%' ;

    sql := '
create table newtab as
select @cols
from BED_2016_MAR_CIT4114A_FYP1_G_';

    sql := replace(sql, '@cols', cols);

    execute immediate sql;
end;

select * 
from newtab;

答案 1 :(得分:0)

看起来问题出在where条件:

where table_name='BED_2016_MAR_CIT4114A_FYP1_G_' 
                    and column_name like '%na%'

删除table_name的条件。您已经从BED_2016_MAR_CIT4114A_FYP1_G_中进行选择,因此只会显示该表中的列。

以下是查询的更简化版本:

select column_name 
from BED_2016_MAR_CIT4114A_FYP1_G_
where column_name like '%na%'

希望有所帮助