【问题标题】:query each column of a table in a loop - Oracle Database循环查询表的每一列 - Oracle 数据库
【发布时间】:2012-07-25 11:37:26
【问题描述】:

我正在使用 oracle 数据库,我基本上需要做的是计算某个表中每列的 NULL 字段数。

类似的东西:

DECLARE
    BlankCount number(20);
    i number(2) := 1;

BEGIN
    loop that would take each column individualy and exit after the last one
        SELECT COUNT(*) INTO BlankCount FROM name_of_my_table
        DBMS_OUTPUT.PUT_LINE('Column '||i||' has '||BlankCount||' empty cells');
        i := i + 1;
    END LOOP;
END;

我只是找不到任何可以做循环部分的东西。 如果不只是给它们编号(用 i)我可以显示列名(但这不是很重要),那也很好。

谢谢!

【问题讨论】:

    标签: sql oracle loops


    【解决方案1】:

    类似这样的:

    declare 
    
      mytable varchar(32) := 'MY_TABLE';
    
      cursor s1 (mytable varchar2) is 
                select column_name 
                from user_tab_columns
                where table_name = mytable
                and nullable = 'Y';
    
      mycolumn varchar2(32);
      query_str varchar2(100);    
      mycount number;
    
    begin
    
      open s1 (mytable);
    
      loop
         fetch s1 into mycolumn; 
             exit when s1%NOTFOUND;
    
         query_str := 'select count(*) from ' || mytable || ' where '  || mycolumn || ' is null';
    
         execute immediate query_str into mycount;
    
         dbms_output.put_line('Column ' || mycolumn || ' has ' || mycount || ' null values');
    
      end loop;
    end; 
    

    【讨论】:

      【解决方案2】:

      尝试使用游标方法和Dynamic SQL,如本主题所述:How to loop through columns in an oracle pl/sql cursor

      HTH。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-27
        • 1970-01-01
        • 2017-09-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多