2010-05-28 81 views
0

如何檢查給定表中的任何列是否只有空值或空字符串值?我能以某種方式擴展數據庫中的每個表嗎?檢查空列

回答

1

您通常無法對錶中所有列的查詢進行查詢。你必須選擇你想要的列。爲了解決這個問題,你需要動態的sql和information_schema視圖。

+0

我意識到我必須使用動態sql。這是爲了維護 – picknick 2010-05-28 18:00:11

2

Here是一個存儲過程,用於在數據庫中查找任意值。這是一個相當小的修改,使其搜索空列。

該過程生成數據庫中所有表和所有列的列表,並創建一個用於存儲結果的臨時表。然後它生成一個動態SQL並使用INSERT INTO ... EXEC填充結果表。

2

這裏的a runnable example關閉StackOverflow的數據庫:

-- Look for NULLs 


DECLARE @sql AS varchar(max) 

SELECT @sql = COALESCE(@sql + ' UNION ALL ', '') + sql 
FROM (
SELECT 'SELECT ''' + c.TABLE_NAME + '.' + c.COLUMN_NAME + ''' AS COLUMN_NAME, COUNT(NULLIF(' + QUOTENAME(c.COLUMN_NAME) + ', '''')) AS NON_NULL_COUNT, COUNT(*) AS TOTAL_COUNT FROM ' + QUOTENAME(c.TABLE_CATALOG) + '.' + QUOTENAME(c.TABLE_SCHEMA) + '.' + QUOTENAME(c.TABLE_NAME) AS sql 
FROM INFORMATION_SCHEMA.COLUMNS AS c 
INNER JOIN INFORMATION_SCHEMA.TABLES AS t 
ON t.TABLE_CATALOG = c.TABLE_CATALOG 
AND t.TABLE_SCHEMA = c.TABLE_SCHEMA 
AND t.TABLE_NAME = c.TABLE_NAME 
WHERE c.DATA_TYPE IN ('nvarchar', 'varchar') 
UNION ALL 
SELECT 'SELECT ''' + c.TABLE_NAME + '.' + c.COLUMN_NAME + ''' AS COLUMN_NAME, COUNT(' + QUOTENAME(c.COLUMN_NAME) + ') AS NON_NULL_COUNT, COUNT(*) AS TOTAL_COUNT FROM ' + QUOTENAME(c.TABLE_CATALOG) + '.' + QUOTENAME(c.TABLE_SCHEMA) + '.' + QUOTENAME(c.TABLE_NAME) AS sql 
FROM INFORMATION_SCHEMA.COLUMNS AS c 
INNER JOIN INFORMATION_SCHEMA.TABLES AS t 
ON t.TABLE_CATALOG = c.TABLE_CATALOG 
AND t.TABLE_SCHEMA = c.TABLE_SCHEMA 
AND t.TABLE_NAME = c.TABLE_NAME 
WHERE c.DATA_TYPE NOT IN ('nvarchar', 'varchar') 
AND c.IS_NULLABLE = 'YES' 
) AS checks 

SET @sql = 'SELECT * FROM (' + @sql + ') AS checks WHERE NON_NULL_COUNT = 0' 

EXEC (@sql) 

有幾件事情需要注意:

有兩列能找到,這是完全空/空:

Posts.OwnerDisplayName,Bdges .CreationDate

它將nvarchar和varchar列的''轉換爲NULL(如果您有char或nchar列,則必須c這個)