2017-04-13 110 views
0

我有以下查詢,它返回包含列PROGRAM_ID列的所有表。有沒有辦法可以在包含列PROGRAM_ID的數據庫中的所有表上返回所有不同的值?獲取跨多個表的特定列的所有不同值

select table_name from all_tab_columns where column_name = 'PROGRAM_ID'; 
+1

我不認爲這是可能的,而無需使用'工會all'通過返回的所有表:這將使用SQL * Plus和SQL Developer的variableprint命令打開具有結果的參考指針,在這個演示您的查詢。 –

+0

你可以通過動態SQL來完成 –

回答

1

您可以生成一個SQL查詢,您可以再複製和手工粘貼:

select case when rownum > 1 then 'union ' end 
    || 'select program_id from ' || owner || '.' || table_name 
from all_tab_columns where column_name = 'PROGRAM_ID'; 

產生的輸出,如:

select program_id from SYS.V_$SQLAREA_PLAN_HASH 
union select program_id from SYS.V_$SQLAREA 
union select program_id from SYS.V_$SQL 
union select program_id from SYS.GV_$SQLAREA 
union select program_id from SYS.GV_$SQLAREA_PLAN_HASH 
union select program_id from SYS.GV_$SQL 
union select program_id from MY_SCHEMA.TABLE_A 
union select program_id from MY_SCHEMA.TABLE_B 
union select program_id from MY_SCHEMA.TABLE_C 

所以你可能要篩選的用戶是檢索;或者如果您只對自己的模式中的表感興趣,則切換到user_tab_columns(並丟失owner部分)。

如果您想一次性識別和查詢表,您可以做同樣的事情,但作爲動態SQL。

var rc refcursor; 

declare 
    l_stmt clob; 
begin 
    select listagg(case when rownum > 1 then 'union ' end 
    || 'select program_id from ' || owner || '.' || table_name, ' ') 
    within group (order by null) 
    into l_stmt 
    from all_tab_columns where column_name = 'PROGRAM_ID'; 

    open :rc for l_stmt; 
end; 
/

print rc 
相關問題