如何从all_tables中选择表格?

时间:2012-09-11 14:29:59

标签: sql oracle

我有以下表名模板,最后有一对同名和一个数字:fmj.backup_semaforo_geo_THENUMBER,例如:

select * from fmj.backup_semaforo_geo_06391442
select * from fmj.backup_semaforo_geo_06398164
...

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

    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表名称数据:

TABLE_NAME
----------
BACKUP_SEMAFORO_GEO_06391442
BACKUP_SEMAFORO_GEO_06398164
...

如何在不获取all_tables输出的情况下实现这一目标?

感谢。

2 个答案:

答案 0 :(得分:2)

据推测,您当前的查询正在获取ORA-00904: "CALLE": invalid identifier,因为子查询没有名为CALLE的列。不幸的是,您不能在运行时为查询提供表名,不幸的是,必须诉诸dynamic SQL

这样的事情将循环遍历所有表格,并且每个表格都会从每个表格中获取CALLE的所有值,然后您可以循环遍历。我已经使用DBMS_OUTPUT来显示它们,假设您在SQL * Plus中执行此操作或者可以处理它的内容;但是你可能想和他们做点什么。

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;
/

答案 1 :(得分:0)

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

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;