0

我正在尋求從SQL Server 2005上開發的遺留系統中清理遷移項目中的數據,但業務的第一順序是要弄清楚哪些列不是'沒有真正使用。SQL Server查詢返回表的字段中的空內容的百分比

我的方法背後的一般邏輯是識別大多數爲空白的列(即大多數或所有行包含該列中的空值,在該表中)。這將作爲一個存儲過程,其中理想的輸出會是這樣執行的:

TABLE: contacts (10000 records) 
--------------------------------- 
FIELD: id | 0 (0%) Null Records 
FIELD: username | 0 (0%) Null Records 
FIELD: phonenumber | 8,200 (82%) Null Records 
FIELD: email | 300 (3%) Null records 
FIELD: icq | 9,900 (99%) Null Records 
FIELD: zip | 100 (1%) Null Records 

這裏的陷阱:一些表有超過100列,做到了真正的鑰匙通過的列是程序循環給定的表,所以我不必鍵入一長串字符串來運行查詢。如何做到這一點的任何幫助將是偉大的,

謝謝。

+1

'SELECT * FROM YourDatabase.INFORMATION_SCHEMA.COLUMNS' – 2012-01-11 05:01:39

回答

2

您可以使用列的元數據來創建這樣一些疑問:

select 'select ''' + table_name + ''' table_name, ''' 
+ column_name + ''' column_name, count(*) nullcount ' 
+ 'from [' + table_name + '] where [' + column_name + '] is null ' 
from information_schema.columns 

如果你運行上面的查詢,你會得到選擇查詢列表。複製粘貼到文本編輯器,並插入之間選擇「UNION ALL」,它看起來就像這樣:

select 'companies' table_name, 'id' column_name, count(*) nullcount from [companies] where [id] is null 
union all 
select 'companies' table_name, 'code' column_name, count(*) nullcount from [companies] where [code] is null 
union all 
... 

然後運行這些被聯合選擇。

對於表列表,您可以對information_schema.tables中的元數據使用相同的技巧。

然後使用vlookup在excel中組合兩個列表,或使用information_schema.tables和information_schema.columns爲子查詢構建更復雜的查詢。

+0

太好了 - 非常感謝。 – Yaaqov 2012-01-11 17:16:19