每列的SQL Unpivot

时间:2014-10-13 21:58:06

标签: sql tsql multiple-columns unpivot

我有以下查询适用于所选的4列,但问题是我需要选择表的每一列(大约有50列)。有没有更简单的方法来做这个而不包括SELECT和IN语句中的50列中的每一列。我也意识到可能存在数据类型问题。返回的数据只有一行。

SELECT g.property, 
   g.value 
FROM   (SELECT applicationversion, 
           ftpservername, 
           smtpservername, 
           Cast(numberofservers AS NVARCHAR(max)) AS numberofservers 
    FROM   globals) Person 
   UNPIVOT (value 
           FOR property IN (applicationversion, 
                            ftpservername, 
                            smtpservername, 
                            numberofservers)) AS g; 

2 个答案:

答案 0 :(得分:3)

请试试这个:

DECLARE @sql AS NVARCHAR(MAX)
DECLARE @cols1 AS NVARCHAR(MAX)
DECLARE @cols2 AS NVARCHAR(MAX)

SELECT @cols1= ISNULL(@cols1 + ',','') + QUOTENAME(name)
FROM (select c.name from sys.tables t
inner join sys.columns c on c.object_id = t.object_id
where t.name = 'globals'
 ) cols1

SELECT @cols2= ISNULL(@cols2 + ',cast(','cast(') + QUOTENAME(name) + ' as nvarchar(max))'+ QUOTENAME(name) 
FROM (select c.name from sys.tables t
inner join sys.columns c on c.object_id = t.object_id
where t.name = 'globals'
 ) cols2


SET @sql =
  N'SELECT g.property, g.value  
FROM   (SELECT ' + @cols2 + '  
    FROM  globals) Person 
   UNPIVOT (value 
           FOR property IN (' + @cols1 +')) AS g; '

EXEC sp_executesql @sql

它不漂亮,当然可以改进,但它应该有用。

答案 1 :(得分:1)

jpw的版本略有改进

input.error ~ label {
    color: red;
}