检查空列

时间:2010-05-28 17:47:38

标签: sql tsql

如何检查给定表中的任何列是否只有空值或空字符串值?我能以某种方式为数据库中的每个表扩展它吗?

3 个答案:

答案 0 :(得分:2)

Here是用于在数据库中查找任意值的存储过程。这是一个相当小的修改,使它搜索空列。

该过程生成数据库中所有表和所有列的列表,并创建用于存储结果的临时表。然后它生成一个动态SQL并使用INSERT INTO ... EXEC来填充结果表。

答案 1 :(得分:2)

这是StackOverflow数据库的a runnable example

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

有几点需要注意:

它找到两列完全为NULL /空白:

Posts.OwnerDisplayName,Bdges.CreationDate

对于nvarchar和varchar列,它将''转换为NULL(如果你有char或nchar列,你必须改变它)

答案 2 :(得分:1)

通常,您不能对表中的所有列的查询设置条件。您必须选择所需的列。要解决此问题,您需要动态sql和information_schema视图。