仅使用oracle中的动态sql的NUMBER数据类型的列的行数

时间:2014-04-09 17:32:33

标签: oracle count dynamic-sql

我只是为架构中的每个表执行了行计数。 现在我需要数据类型为NUMBER的表中的列数。 我不知道如何获取每个表的单个NUMBER数据类型列的行数?

DECLARE
  t_c1_tname user_tables.table_name%TYPE;
  t_command  VARCHAR2(200);
  row_count INTEGER;
  CURSOR c1 IS SELECT table_name FROM user_tables ORDER BY table_name;
BEGIN 
  OPEN c1;
  LOOP
        FETCH c1 INTO t_c1_tname;
        EXIT WHEN c1%NOTFOUND;
        t_command  := 'SELECT COUNT(*) FROM '||t_c1_tname ;
        execute immediate t_command into  row_count;
        dbms_output.put_line('Table : '|| t_c1_tname || 'Count : '|| row`enter code here`_count);
  END LOOP;
  CLOSE c1;
END;

1 个答案:

答案 0 :(得分:0)

我认为这就是你想要的:

set serveroutput on
declare
  not_null_count INTEGER;
  null_count INTEGER;
begin
  for r in (
    select utc.table_name, utc.column_name
    from user_tab_columns utc
    where data_type = 'NUMBER'
    order by utc.table_name, utc.column_id
  )
  loop
    execute immediate 'select count("' || r.column_name || '"),
      count(nvl2("' || r.column_name || '", null, 1))
      from "' || r.table_name || '"'
    into not_null_count, null_count;
    dbms_output.put_line('Table: ' || r.table_name
      || ' column: ' || r.column_name
      || ' not-null: ' || not_null_count
      || ' null: ' || null_count);
  end loop;
end;
/

如果我创建了一些数据:

create table t42(num1 number, num2 number, str1 varchar2(5));

insert into t42 values (1, 2, 'a');
insert into t42 values (3, 4, 'b');
insert into t42 values (5, null, 'c');

然后该块显示:

Table: T42 column: NUM1 not-null: 3 null: 0
Table: T42 column: NUM2 not-null: 2 null: 1

如果您要查询all_tab_columns,则需要获取并使用表所有者:

  for r in (
    select atc.owner, atc.table_name, atc.column_name
    from all_tab_columns atc
    where data_type = 'NUMBER'
    order by atc.owner, atc.table_name, atc.column_id
  )
  loop
    execute immediate 'select count("' || r.column_name || '"),
      count(nvl2("' || r.column_name || '", null, 1))
      from '"' || r.owner || '"."' || r.table_name || '"'
    into not_null_count, null_count;