首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在select from all_tables上选择表?

如何在select from all_tables上选择表?
EN

Stack Overflow用户
提问于 2012-09-11 22:29:59
回答 2查看 10.8K关注 0票数 0

我有下面的表名模板,有一对同名的,末尾有一个数字: fmj.backup_semaforo_geo_THENUMBER,例如:

代码语言:javascript
复制
select * from fmj.backup_semaforo_geo_06391442
select * from fmj.backup_semaforo_geo_06398164
...

假设我需要从使用'fmj.backup_semaforo_geo_%‘过滤器成功的每个表中选择一列,我尝试这样做:

代码语言:javascript
复制
    SELECT calle --This column is from the backup_semaforo_geo_# tables
     FROM (SELECT table_name
      FROM all_tables
     WHERE owner = 'FMJ' AND table_name LIKE 'BACKUP_SEMAFORO_GEO_%');

但是我正在获取all_tables表的名称数据:

代码语言:javascript
复制
TABLE_NAME
----------
BACKUP_SEMAFORO_GEO_06391442
BACKUP_SEMAFORO_GEO_06398164
...

在没有得到all_tables输出的情况下,我如何实现这一点呢?

谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-09-11 23:34:48

假设您当前的查询获取的是ORA-00904: "CALLE": invalid identifier,因为子查询没有名为CALLE的列。不幸的是,您不能在运行时为查询提供表名,而必须求助于dynamic SQL

类似这样的代码将遍历所有的表,并且对于每个表,将从每个表中获得CALLE的所有值,然后您可以遍历这些值。我已经使用了DBMS_OUTPUT来显示它们,假设您是在SQL或其他可以处理该问题的工具中执行此操作;但是您可能希望使用它们执行其他操作。

代码语言:javascript
复制
set serveroutput on

declare
    -- declare a local collection type we can use for bulk collect; use any table
    -- that has the column, or if there isn't a stable one use the actual data
    -- type, varchar2(30) or whatever is appropriate
    type t_values is table of table.calle%type;
    -- declare an instance of that type
    l_values t_values;
    -- declare a cursor to generate the dynamic SQL; where this is done is a
    -- matter of taste (can use 'open x for select ...', then fetch, etc.)
    -- If you run the query on its own you'll see the individual selects from
    -- all the tables
    cursor c1 is
        select table_name,
            'select calle from ' || owner ||'.'|| table_name as query
        from all_tables
        where owner = 'FMJ'
        and table_name like 'BACKUP_SEMAFORO_GEO%'
        order by table_name;
begin
    -- loop around all the dynamic queries from the cursor
    for r1 in c1 loop
        -- for each one, execute it as dynamic SQL, with a bulk collect into
        -- the collection type created above
        execute immediate r1.query bulk collect into l_values;
        -- loop around all the elements in the collection, and print each one
        for i in 1..l_values.count loop
            dbms_output.put_line(r1.table_name ||': ' || l_values(i));
        end loop;
    end loop;
end;
/
票数 2
EN

Stack Overflow用户

发布于 2012-09-11 23:20:50

可以是PLSQL程序中的动态SQL;

代码语言:javascript
复制
for a in (SELECT table_name
            FROM all_tables
            WHERE owner = 'FMJ' AND table_name LIKE 'BACKUP_SEMAFORO_GEO_%')
LOOP
   sql_stmt := ' SELECT calle FROM' || a.table_name;
   EXECUTE IMMEDIATE sql_stmt;
   ...
   ...
END LOOP;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12372065

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档