找出Oracle中给定行的表中具有NULL值的所有列

时间:2015-04-08 11:44:27

标签: sql oracle

例如,如果表格如下所示

ID  FIRST_NAME LAST_NAME  START_DAT END_DATE      SALARY CITY      DESCRIPTION
---- ---------- ---------- --------- --------- ---------- -------------------
01   Jason      Martin     25-JUL-96 NULL         1234.56 NULL       Programmer
02   Alison     Mathews    21-MAR-76 21-FEB-86    6661.78 Vancouver  Tester

对于记录ID" 1",END_DATECITY具有空值。如何在单个查询中获取这些值?

2 个答案:

答案 0 :(得分:2)

您可以使用case找出具有NULL值的内容并将结果连接在一起:

select ((case when id is null then 'id;' end) ||
        (case when first_name is null then 'firstname;' end) ||
        . . .
        (case when description is null then 'description;' end)
       ) as NullColumns
from table;

注意:Oracle将NULL值视为连接运算符的空字符串。

答案 1 :(得分:2)

您可以使用此功能:

create or replace function list_null_cols(i_table in varchar2, 
  i_filter in varchar2 default '') return varchar2 is

  v_sql varchar2(32000);
  cursor cols is 
    select column_name cn from user_tab_cols 
      where table_name = upper(i_table) and nullable='Y';
  ret varchar2(32000);
begin
  for c in cols loop
    v_sql := v_sql || 'max(nvl2('||c.cn||',null,'''||c.cn||',''))||';
  end loop;
  if length(v_sql) = 0 then 
    return 'no columns found'; 
  end if;
  v_sql := 'select '||rtrim(v_sql, '|| ') ||' from '||i_table||' '||i_filter;
  begin 
    execute immediate v_sql into ret;
  exception when others then
    return 'error: '||sqlerrm;
  end;
  return rtrim(ret, ',');
end;

第一个参数是表名,第二个是可选的where...过滤器。如果省略第二个参数,将分析表中的所有行,如示例所示:

create table test_table (ID varchar2(2), FIRST_NAME number, LAST_NAME number,  
  START_DATE number, END_DATE number, SALARY number, CITY number, DESCRIPTION number);

insert into test_table values ('01', 1, 1, 1, null, 1, 1, 1);
insert into test_table values ('02', 2, 2, 2, 2, 2, null, 2);

select list_null_cols('test_table') list from dual;

LIST               
-------------------
END_DATE,CITY      

select list_null_cols('test_table', ' where id=''01''') list from dual;

LIST               
-------------------
END_DATE      

select list_null_cols('test_table', ' where salary=2') list from dual;

LIST               
-------------------
CITY