选择除仅具有空值的列以外的所有列

时间:2010-12-09 10:54:56

标签: sql sql-server-2005

有没有办法选择某个表的列名,除了那些只有空值的列,而不知道该表有多少列。

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

应该导致:

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

谢谢!

3 个答案:

答案 0 :(得分:1)

使用以下内容创建存储过程:

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

答案 1 :(得分:1)

试试这个,它不是最整洁但可行,只需将@Table设置为您的表名。

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

答案 2 :(得分:0)

使用此结构,您可以在存储过程中执行查询,该过程允许您询问表的每个列名称,以及它是否具有空值而不关心您的表有多少列

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