2014-07-14 89 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這樣的技術。

相關問題