简体   繁体   中英

How to perform a select from table names returned by another query?

I have a query that returns table names I need, for example

select table_name from all_tables where lower(table_name) like 'test_table%';

How do I perform a select from all those tables by their names that I receive as result of the query? I tried concatenate them and use "execute immediate", but I couldn't make it work.

I tried:

execute immediate 'select value from '|| select listagg(table_name, ', ') within group (order by table_name) from all_tables where table_name like 'test_table%';

Here is a little example to execute a "select count(*)" on a list of tables returned by a query :

select
TRUNC(SYSDATE) AS COUNT_DATE,
table_name,
to_number(
extractvalue(
xmltype(
dbms_xmlgen.getxml('select count(*) c from '||owner||'.'||table_name))
,'/ROWSET/ROW/C')) as count
from
all_tables where rownum < 3
order by
table_name

dbms_xmlgen.getxml allows you to execute a dynamically created query and returns the result as XML from which you can extract the values with extractvalue. Usefull when the query you want to issue returns a single row.

Regards

L

You could do something like:

select 'select * from '||owner||'.'||table_name||';'
from   all_tables
where  lower(table_name) like '%test_table%';

Then copy and paste the results and run the statements, either as a script or individually as per your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM