我想编写一个查询来从表中获取数据,除了一些列,这些列的开头名称在通配符标准中给出,如下面的示例伪代码。在甲骨文上有可能吗?
(这可以通过添加select子句的列名来完成。但是假设将来会添加新列,我想编写更通用的代码)
例如
Employee(id , name , age, gender)
select *
from table_name
where column_name not like a%
查询后,它应显示一个带
的表Employee(id , name . gender)
年龄栏不存在,因为我们未在结果中包含
答案 0 :(得分:2)
您可以尝试使用一些动态SQL:
declare
vSQL varchar2(32767);
vClob clob;
begin
/* build the query */
select distinct 'select ' || listagg(column_name, ',') within group (order by column_name) over (partition by table_name)|| ' from ' || table_name
into vSQL
from user_tab_columns
where table_name = 'EMPLOYEE'
and column_name not like 'A%';
/* print the query */
dbms_output.put_line(vSQL);
/* build an XML */
select DBMS_XMLGEN.getXML(vSQL)
into vClob
from dual;
dbms_output.put_line(vClob);
/* build a CLOB with all the columns */
vSQL := replace (vSQL, ',', ' || '' | '' || ' );
execute immediate vSQL into vClob;
dbms_output.put_line(vClob);
end;
通过这种方式,您可以动态构建一个查询,该查询将提取与模式匹配的所有列。
构建查询后,问题是如何获取它,因为您事先并不知道要获取哪些列。 在示例中,我创建了一个XML和一行;您可以根据需要以不同方式使用查询。
答案 1 :(得分:1)
重复,但我喜欢写PL,所以你可以这样做,创建一个临时表,然后从中选择*:
declare
your_table varchar2(40) := 'CHEMIN';
select_to_tmp varchar2(4000) := 'create table ttmp as select ';
begin
-- drop temporary table if exists
begin
execute immediate 'drop table ttmp';
Exception
When others Then
dbms_output.put_line(SQLERRM);
end;
for x in (
select column_name from all_tab_columns
where table_name=your_table
and column_name not in (
-- list columns you want to exclude
'COL_A'
, 'COL_B'
)
)
loop
select_to_tmp := select_to_tmp|| x.column_name ||',';
dbms_output.put_line(x.column_name);
end loop;
-- remove last ','
select_to_tmp := substr(select_to_tmp, 1, length(select_to_tmp) -1);
-- from your table
select_to_tmp := select_to_tmp||' from '||your_table;
-- add conditions if necessary
-- select_to_tmp := select_to_tmp|| ' where rownum < 1 '
dbms_output.put_line(select_to_tmp);
-- then create the temporary table using the query you generated:
execute immediate select_to_tmp;
end;
/
SELECT * FROM ttmp;