3

This question is the exact opposite of SQL: Select columns with NULL values only.

Given a table with 1024 columns, how to find all columns WITHOUT null values?

Input:a table with 1024 columns

Output:col1_name(no null values) col2_name(no null values)...

6
  • well, a nonwide table can have a maximum of 1,024 columns, and a wide table can have up to 30,000 Commented Feb 8, 2017 at 21:08
  • did you read the first two comments on that answer? Commented Feb 8, 2017 at 21:10
  • @scsimon I did. If you replace it, ` you'll get a list of columns that have at least 1 record with a value` Commented Feb 8, 2017 at 21:18
  • Write a query with as many count expressions as you have columns and see which are 0. Commented Feb 8, 2017 at 21:28
  • What you want for 'output' is a bit ambiguous. Are you just wanting the names of all the columns that have no nulls in them in any row in the table? I provided that solution, but upon re-reading, I'm not sure if that's exactly what you were asking for. Commented Feb 10, 2017 at 17:01

2 Answers 2

4

If you want to avoid using a CURSOR, this method will simply list out the column names of any columns that have no NULL values in them anywhere in the table... just set the @TableName at the top:

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

As a bonus, the results are in a temp table, #Results, so you can query to get any information you want... counts, etc.

Sign up to request clarification or add additional context in comments.

Comments

0

i modified the Select columns with NULL values only.

to work for your case :

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.