2011-04-05 51 views
1

我在oracle數據庫中有很多列,有些新增了值。我想知道哪些列的值不是0或空值。所以我正在尋找一些有用的值至少在一行中存在的列名。如何找到具有非空值的列?

我該怎麼做?

更新:這聽起來非常接近。我如何修改以適應我的需求?

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

回答

1

您可以使用dba_tab_cols視圖查詢所有列,然後查看是否有列的值不爲0或爲空。

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. 另外,檢查「不等於零」對於不是整數的列可能無效,並且如果列的日期數據類型爲列,則會發生錯誤。您需要爲這些案例添加條件。使用dba_tab_cols中的Data_type列並根據需要添加條件。

0

對不起,我第一次誤讀了這個問題。

this post Oracle的論壇

假設你的統計數據是最新的:

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') 

在那裏將結果限制在您的表格中。

+1

他想要列的列表,而不是一組行。 – JNK 2011-04-05 17:14:10

+0

這是一個更好的,但我也想添加值爲0或0.00等的列(即..對我的目的沒有用)。 – aartist 2011-04-07 15:11:29

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()只需要一行,並且默默/透明地進行優化。附:將您的測試添加到子查詢中。

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

這個發現並不具有任何值,以便您可以執行到任何操作欄。

+0

這不排除「具有非零值或空值」的列。它將包括所有行都具有零值的列。 – GargantuChet 2012-09-19 01:44:32