获取表的列名,它们始终为null

时间:2017-03-26 15:23:54

标签: sql sql-server

我有一个包含100列的表格。其中一些不包含任何价值。

有没有办法使用SQL查询列出这些列?

2 个答案:

答案 0 :(得分:1)

仅当此列的所有行都为null时,

MAX(col)才为null。因此,请检查每个列,并连接表达式为null的名称。

select 
  'null columns: ' ||
  case when max(col1) is null then 'col1 ' else '' end ||
  case when max(col2) is null then 'col2 ' else '' end ||
  case when max(col3) is null then 'col3 ' else '' end ||
  case when max(col4) is null then 'col4 ' else '' end ||
  ...
from mytable;

答案 1 :(得分:0)

假设您使用的是Sql-Server,只需将表名分配给dbo.MyTable

即可

在此示例中,我假设DECLARE @strTablename varchar(100) = 'dbo.MyTable' DECLARE @strQuery varchar(max) = '' DECLARE @strUnPivot as varchar(max) = ' UNPIVOT ([Count] for [Column] IN (' CREATE TABLE ##tblTemp([Column] varchar(50), [Count] Int) SELECT @strQuery = ISNULL(@strQuery,'') + 'Count([' + name + ']) as [' + name + '] ,' from sys.columns where object_id = object_id(@strTablename) and is_nullable = 1 SELECT @strUnPivot = ISNULL(@strUnPivot,'') + '[' + name + '] ,' from sys.columns where object_id = object_id(@strTablename) and is_nullable = 1 SET @strQuery = 'SELECT [Column],[Count] FROM ( SELECT ' + SUBSTRING(@strQuery,1,LEN(@strQuery) - 1) + ' FROM ' + @strTablename + ') AS p ' + SUBSTRING(@strUnPivot,1,LEN(@strUnPivot) - 1) + ')) AS unpvt ' INSERT INTO ##tblTemp EXEC (@strQuery) SELECT [Column] from ##tblTemp Where [Count] =0 DROP TABLE ##tblTemp 是表名

<a href="play.php?choose=2">
  <div id="champbox" style="background-image: url(http:xxx.jpg);float:right;"></div>
</a>