plsql列出包含空值的所有table.column

时间:2017-01-23 12:49:04

标签: sql oracle

我想找到一组表中包含空值的所有列。

我可以找到表名和列名

SELECT TABLE_NAME, COLUMN_NAME 
FROM user_tab_cols 
where nullable='Y'
      and table_name in ('myTalbe', 'myTable2');

并检查是否为空

select count(*) from myTable where myColumn is null;

但我怎么能把这个结果作为结果

table_name     column_name
myTable        myColumn
myTable        myCol2
myTable2       col4

2 个答案:

答案 0 :(得分:1)

一种方法可能是一些动态SQL,但这需要一些PL / SQL代码;以下只使用SQL来获得所需的结果:

select *
from (
        select table_name,
               column_name,
               to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from '||table_name || ' where ' || column_name || ' is null')),'/ROWSET/ROW/C')) as rowcount
        from user_tab_columns
        where nullable='Y'
          and table_name in ('myTalbe', 'myTable2')
     )
where rowcount > 0 

这可能是一种动态SQL的方法:

declare
    type tableOfNumber is table of number;
    type tableOfChar   is table of varchar2(30);
    --
    vSQl            varchar2(4000);
    vListNumbers    tableOfNumber;
    vListTables     tableOfChar;
    vListColumns    tableOfChar;
begin
    select listagg( 'select ''' ||
                       table_name || ''' as table_name, ''' || 
                       column_name || ''' as column_name, count(*) as rowCount from ' || 
                       table_name || 
                       ' where ' || 
                       column_name || 
                       ' is null having count(*) > 0' ,
                     ' UNION ALL '
                   ) within group ( order by table_name, column_name)
    into vSQL
    from user_tab_columns
    where nullable='Y'
          and table_name in ('myTalbe', 'myTable2');
    --
    dbms_output.put_line(vSQL);


    /* whatever you may want to do with the query */


    /* for example, fetch into some variables and print the result */
    execute immediate vSQL
    bulk collect into vListTables, vListColumns, vListNumbers;
    --
    if vListTables.count() > 0 then
        for i in vListTables.first .. vListTables.last loop
            dbms_output.put_line('Table ' || vListTables(i) ||
                                    ', column ' || vListColumns(i) ||
                                    ', number of nulls: ' || vListNumbers(i)
                                  );
        end loop;
    end if;
end;

答案 1 :(得分:0)

这是我写一段时间的例行程序。它将输出所需的DDL,以使那些可以为空(但不包含任何空值)的列不可为空。

https://connormcdonald.wordpress.com/2016/03/11/tightening-up-your-data-model/

它可以为架构或单个表执行任务。

相关问题