大家好,我有桌子:
Expected Date| 00:00 | 01:00 | 02:00 |03:00|
20160428 | 11179 | [NULL]| [NULL]| [NULL]
20160428 | 11181 | [NULL] |[NULL] |[NULL]
20160428 | 11182 | [NULL] |[NULL] |[NULL]
20160426 | [NULL] | [NULL] |[NULL] |11180
20160426 | [NULL] | [NULL] |[NULL] |11189
表动态数据。如何选择只获取包含数据的列(00:00和03:00),但不选择NULL垂直列(01:00和02:00)。
我想要的是什么:
|Expected Date | 00:00 | 03:00
|20160428 | 11179 | [NULL]
|20160428 | 11181 | [NULL]
|20160428 | 11182 | [NULL]
|20160426 | [NULL] | 11180
|20160426 | [NULL] | 11189
答案 0 :(得分:0)
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 = '<table_name>'
OPEN getinfo
FETCH NEXT FROM getinfo into @col
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @cmd = 'IF NOT EXISTS (SELECT top 1 * FROM <table_name> WHERE [' + @col + '] IS NULL) BEGIN SELECT @tmp = ''' + @col + ','' end'
exec sp_executesql @cmd, N'@tmp varchar(30) out', @tmp out
if @tmp IS NOT NULL
BEGIN
SELECT @nonNullCol = CONCAT(@nonNullCol, @tmp)
END
SELECT @tmp = null
FETCH NEXT FROM getinfo into @col
END
CLOSE getinfo
DEALLOCATE getinfo
PRINT @nonNullCol
SELECT @cmd = 'SELECT ' + LEFT(@nonNullCol, LEN(@nonNullCol)-1) + ' FROM <table_name>'
EXEC(@cmd)