获取跨多个表的特定列的所有不同值

时间:2017-04-13 17:29:47

标签: sql oracle

我有以下查询返回包含列PROGRAM_ID的所有表。有没有办法可以在包含列PROGRAM_ID的数据库中的所有表中返回所有不同的值?

select table_name from all_tab_columns where column_name = 'PROGRAM_ID';

1 个答案:

答案 0 :(得分: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。这将打开一个包含结果的引用游标,在本演示中使用SQL * Plus和SQL Developer variableprint命令:

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
相关问题