sql查询在模式中查找table_name和count(table_name)

时间:2014-07-10 08:55:47

标签: sql oracle

用于在模式中查找table_namecount(table_name)的SQL查询:

示例:

我从此查询中获取table_name:

SELECT * FROM USER_TABLES

和来自

的count(table_name)
select count(*) from employee
select count(*) from dept
select count(*) from subjects

现在我想得到这样的结果:

table_name     count(table_name)
Employee        100
dept            21
subjects        56

2 个答案:

答案 0 :(得分:2)

试试这个

select
       table_name,
       to_number(
         extractvalue(
           xmltype(
             dbms_xmlgen.getxml('select count(*) c ' ||
                                ' from '||owner||'.'||table_name))
           ,'/ROWSET/ROW/C')) count
   from all_tables
  where table_name In ( 
  SELECT table_name from user_tables )

或使用加入

select
       a.table_name,
       to_number(
         extractvalue(
           xmltype(
             dbms_xmlgen.getxml('select count(*) c ' ||
                                ' from '||owner||'.'||a.table_name))
           ,'/ROWSET/ROW/C')) count
   from all_tables a JOIN user_tables u ON
  a.table_name=u.table_name  AND a.owner = user 

答案 1 :(得分:1)

看起来像一个简单的UNION ALL的典型用例:

select 
  'Employee' table_name,
  count(*) from employee 
union all
select 
  'dept' table_name,
  count(*) from dept 
union all
select 
  'subjects' table_name,
  count(*) from subjects

如果要自动执行此操作,可以迭代USER_TABLES

declare
  l_cnt pls_integer;
begin
  for cur in (select table_name from user_tables order by table_name)
  loop
    execute immediate 'select count(*) from ' || cur.table_name into l_cnt;
    dbms_output.put_line(cur.table_name || ' ' || l_cnt);
  end loop;
end;

您可以动态构建SQL语句,然后再使用它,而不是简单地打印结果:

declare
  l_sql varchar2(4000);
begin
  for cur in (select table_name from user_tables order by table_name)
  loop
    l_sql := l_sql || ' select ' || cur.table_name || ' as table_name, count(*) as cnt from ' || cur.table_name || ' union all';
  end loop;
  -- remove trailing UNION ALL
  l_sql := regexp_replace(l_sql, 'union all$', '');
  dbms_output.put_line(l_sql);
end;