SQL:仅在表中选择WITHOUT NULL值的列

时间:2017-02-08 21:07:07

标签: sql sql-server sql-server-2008 tsql

这个问题与SQL: Select columns with NULL values only完全相反。

给定一个包含1024列的表,如何找到没有空值的所有列?

输入:a table with 1024 columns

输出:col1_name(no null values) col2_name(no null values)...

2 个答案:

答案 0 :(得分:3)

如果你想避免使用CURSOR,这个方法只会在表格的任何地方列出任何没有NULL值的列的列名...只需将@TableName设置在顶部:

DECLARE @tableName sysname;
DECLARE @sql nvarchar(max);
SET @sql = N'';
SET @tableName = N'Reports_table';

SELECT @sql += 'SELECT CASE WHEN EXISTS (SELECT 1 FROM ' + @tableName + ' WHERE '+ COLUMN_NAME + ' IS NULL) THEN NULL ELSE ''' + COLUMN_NAME +
''' END AS ColumnsWithNoNulls UNION ALL '
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @tableName
SELECT @sql = SUBSTRING(@sql, 0, LEN(@sql) - 10);
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results;
CREATE TABLE #Results (ColumnsWithNoNulls sysname NULL);
INSERT INTO #Results EXEC(@sql);
SELECT * FROM #Results WHERE ColumnsWithNoNulls IS NOT NULL

作为奖励,结果位于临时表#Results中,因此您可以查询以获取您想要的任何信息......计数等。

答案 1 :(得分:0)

我修改了Select columns with NULL values only.

为您的案件工作:

SET ANSI_WARNINGS OFF 

declare @col varchar(255), @cmd varchar(max)

DECLARE getinfo cursor for
SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID = c.Object_ID
WHERE t.Name = 'Reports_table'

OPEN getinfo

FETCH NEXT FROM getinfo into @col

WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @cmd = 'IF (SELECT sum(iif([' + @col + '] is null,1,null)) FROM Reports_table) is null  BEGIN print ''' + @col + ''' end'
    exec(@cmd)

    FETCH NEXT FROM getinfo into @col
END

CLOSE getinfo
DEALLOCATE getinfo

SET ANSI_WARNINGS on