简体   繁体   中英

Select all columns except those with only null values

Is there a way to select the column names of a certain table except those columns with only null values without knowing how many columns the table have.

-------------------------
| col1  | col2   | col3 |
------------------------
| val1  | null   | val2 |
| val1  | null   | null |
| null  | null   | val2 |
-------------------------

Should result in:

------------------------------------
| cols_except_those_with_null_only |
-----------------------------------
| col1                             |
| col3                             |
------------------------------------

Thanks!

Create a stored procedure with following content:

create table #cols (colname varchar(255), nullCount int)

insert into #cols (colname)
select name from syscolumns where id = object_id('tblTest')

declare @c varchar(255)

declare curCols cursor for select colname from #cols
open curCols
fetch next from curCols into @c
while @@fetch_status = 0 begin
  exec ('update #cols set nullCount = (select count(*) from tblTest where ' + @c + ' is not null) where colname = ''' + @c + '''')
  fetch next from curCols into @c
end
close curCols
deallocate curCols

declare @rv table (cols_expect_those_with_null_only varchar(255))

insert into @rv (cols_expect_those_with_null_only)
select colname from #cols
where nullCount > 0

drop table #cols

select * from @rv

Try this, it's not the tidiest but will work, just set @Table to your table name.

DECLARE @Table AS VARCHAR(100)
SET @Table = 'Example'

DECLARE @TempColumn VARCHAR(100)
DECLARE @Sql NVARCHAR(300)
DECLARE @HasNoNulls INT

CREATE TABLE #Columns (
ColumnName VARCHAR(100)
)

DECLARE ColumnCursor CURSOR FOR 
SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.Columns 
WHERE TABLE_NAME = @Table

OPEN ColumnCursor

FETCH NEXT FROM ColumnCursor
INTO @TempColumn

WHILE @@FETCH_STATUS = 0
BEGIN

SET @SQL = 'SELECT @HasNoNullsOut = COUNT(*) FROM ' + @Table + ' WHERE ' + @TempColumn + ' IS NOT NULL'
PRINT @SQL
EXECUTE sp_executesql @SQL, N'@HasNoNullsOut int OUTPUT', @HasNoNullsOut=@HasNoNulls OUTPUT

IF @HasNoNulls > 0
BEGIN
    INSERT INTO #Columns
    VALUES(@TempColumn)
END

FETCH NEXT FROM ColumnCursor
INTO @TempColumn
END

CLOSE ColumnCursor
DEALLOCATE ColumnCursor

SELECT * FROM #Columns

DROP TABLE #Columns

With this structure you can do a query in a store procedure that allows you to ask for each column name of the table and if it has null values without caring how many columns your table has

SELECT a.[name] as 'Table',
  b.[name] as 'Column'
FROM  sysobjects a
INNER JOIN syscolumns b
ON  a.[id] = b.[id]
where table='yourtable'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM