Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 447
picknick Avatar asked Feb 16 '26 09:02

picknick


1 Answers

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
like image 173
wickie79 Avatar answered Feb 19 '26 03:02

wickie79



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!