如何查找具有非空值的列?

时间:2011-04-05 17:09:31

标签: sql oracle

我在oracle数据库中有很多列,一些新的值添加了值。我想找出哪些列的值不是0或null。所以我正在寻找至少在一行中存在某种有用值的列名。

我该怎么做?

更新:听起来非常接近。如何修改它以满足我的需求?

select column_name, nullable, num_distinct, num_nulls
from all_tab_columns
where table_name = 'SOME_TABLE'

4 个答案:

答案 0 :(得分:1)

您可以使用dba_tab_cols视图查询所有列,然后查看是否存在值为0或null的列。

create or replace function f_has_null_rows(
    i_table_name in dba_tab_cols.table_name%type,
    i_column_name in dba_tab_cols.table_name%type
) return number is
v_sql varchar2(200);
v_count number;
begin
  v_sql := 'select count(*) from ' || i_table_name ||
           ' where ' || i_column_name ' || ' is not null and ' 
           || i_column_name  || ' <>0 ';

  execute immediate v_sql into v_count;

  return v_count;
end;
/


select table_name, column_name from dba_tab_Cols
where  f_has_null_rows (table_name, column_name) > 0 
  1. 如果您在某些模式中有同义词,那么您可能会发现某些表格会重复出现。您必须更改代码才能满足要求。

  2. 此外,检查“不等于零”可能对非整数的列无效,并且如果列是date数据类型则会给出错误。您需要为这些案例添加条件。使用dba_tab_cols中的Data_type列并根据需要添加条件。

答案 1 :(得分:1)

Select Column_name
from user_tab_columns
where table_name='EMP' and num_nulls=0;

这会找到没有任何值的列,因此您可以对其执行任何操作。

答案 2 :(得分:0)

抱歉,我第一次误读了这个问题。

来自Oracle论坛的this post

假设您的统计信息是最新的:

SELECT t.table_name,
t.column_name
FROM user_tab_columns t
WHERE t.nullable = 'Y'
AND t.num_distinct = 0;

将返回一个表名和列为空的列表。您可能希望添加以下内容:

AND t.table_name = upper('Your_table_name')

在那里将结果限制在你的桌子上。

答案 3 :(得分:0)

select 'cats' as mycolumname from T 
    where exists (Select id from T where cats is not null)
union
select 'dogs' as mycolumnname from T 
    where exists (select id from T where dogs is not null)

# ad nauseam

是如何在SQL中完成的。编辑:不同风格的SQL可能允许您使用子查询中的LIMIT或TOP'n'进行优化。或者也许他们甚至足够聪明地意识到EXIST()只需要一行并且默默地/透明地进行优化。附:将测试零添加到子查询中。

相关问题