Select all columns except those with only null values

偶尔善良 提交于 2019-12-14 01:27:35

问题


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!


回答1:


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



回答2:


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



回答3:


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'


来源:https://stackoverflow.com/questions/4397438/select-all-columns-except-those-with-only-null-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!