2014-07-14 88 views
2

我有很多具有相同列'customer_number'的表。 我可以通过查询得到所有这些表的列表:如何从它所在的所有表中选择一列?

SELECT table_name FROM ALL_TAB_COLUMNS 
WHERE COLUMN_NAME = 'customer_number'; 

的问题是如何获取所有已获得所有这些表的特定客户数量的记录,但不运行对他们每个人相同的查询。

回答

1

我假设你想自动执行此操作。两种方法。

  1. SQL生成SQL脚本

spool run_rep.sql 
set head off pages 0 lines 200 trimspool on feedback off 

SELECT 'prompt ' || table_name || chr(10) || 

     'select ''' || table_name || 
     ''' tname, CUSTOMER_NUMBER from ' || table_name || ';' cmd 
FROM all_tab_columns 
WHERE column_name = 'CUSTOMER_NUMBER'; 

spool off 

@ run_rep.sql 
  1. PLSQL

类似的想法使用动态SQL:

DECLARE 
    TYPE rcType IS REF CURSOR; 
    rc rcType; 
    CURSOR c1 IS SELECT table_name FROM all_table_columns WHERE column_name = 'CUST_NUM'; 
    cmd VARCHAR2(4000); 
    cNum NUMBER; 
BEGIN 
    FOR r1 IN c1 LOOP 
     cmd := 'SELECT cust_num FROM ' || r1.table_name ; 
     OPEN rc FOR cmd; 
     LOOP 
     FETCH rc INTO cNum; 
     EXIT WHEN rc%NOTFOUND; 
     -- Prob best to INSERT this into a temp table and then 
     -- select * that to avoind DBMS_OUTPUT buffer full issues 
     DBMS_OUTPUT.PUT_LINE ('T:' || r1.table_name || ' C: ' || rc.cust_num); 
     END LOOP; 
     CLOSE rc; 
    END LOOP; 
END; 
2

要从表中获取记录,您必须针对该表编写查询。所以,你无法从指定字段的表中获取所有记录,而无需对这些表中的每一个进行查询。

如果你有兴趣在列的一个子集,该子集的所有表之间共享,你可以使用UNION/UNION ALL操作是这样的:

select * from (
select customer_number, phone, address from table1 
union all 
select customer_number, phone, address from table2 
union all 
select customer_number, phone, address from table3 
) 
where customer_number = 'my number' 

或者,在简单的情况下,你只是想知道哪些表有关于特定客户端的记录

select * from (
select 'table1' src_tbl, customer_number from table1 
union all 
select 'table2', customer_number from table2 
union all 
select 'table3', customer_number from table3 
) 
where customer_number = 'my number' 

否则,您必须单独查询每个表。

1

DBMS_XMLGEN使您能够运行而无需自定义的PL/SQL动态SQL语句。

示例模式

create table table1(customer_number number, a number, b number); 
insert into table1 values(1,1,1); 
create table table2(customer_number number, a number, c number); 
insert into table2 values(2,2,2); 
create table table3(a number, b number, c number); 
insert into table3 values(3,3,3); 

查询

--Get CUSTOMER_NUMBER and A from all tables with the column CUSTOMER_NUMBER. 
-- 
--Convert XML to columns. 
select 
    table_name, 
    to_number(extractvalue(xml, '/ROWSET/ROW/CUSTOMER_NUMBER')) customer_number, 
    to_number(extractvalue(xml, '/ROWSET/ROW/A')) a 
from 
(
    --Get results as XML. 
    select table_name, 
     xmltype(dbms_xmlgen.getxml(
      'select customer_number, a from '||table_name 
     )) xml 
    from user_tab_columns 
    where column_name = 'CUSTOMER_NUMBER' 
); 


TABLE_NAME CUSTOMER_NUMBER A 
---------- --------------- - 
TABLE1  1    1 
TABLE2  2    2 

警告

这些过于通用的解决方案往往有问题。它们不会像普通的旧SQL语句那样执行,而且更可能会遇到错误。一般来说,生产代码应避免使用这些类型的解决方案。但它们对于即席查询仍然非常有用。

此外,此解决方案假定您需要每行中的相同列。如果每一行都不一样,那么事情就会变得更加复杂,您可能需要研究像ANYDATASET这样的技术。

相关问题