将行转置为列 - SQL 2005

时间:2010-11-04 11:54:43

标签: sql sql-server-2005 tsql stored-procedures

我有以下结果集

Status       Wage     --Columns Names (Table)
======       =====   
Employed    10,000  

我需要的是:

Key     Value      DataType
===     =====      ========
Status  Employed   column data type e.g varchar
Wage    10,000     decimal(18,2)

如何在SQL 2005中使用TSQL实现这一目标

2 个答案:

答案 0 :(得分:3)

答案 1 :(得分:1)

可以使用INFORMATION_SCHEMA,UNPIVOT,CAST和EXEC完成。这是一个有效的解决方案。

CREATE TABLE #Data ([Status] int, [Wage] varchar(100), [Tax] decimal(10,3), BigText nvarchar(max))
INSERT #Data VALUES (7, '$12m', 123123.22, 'small island')

SELECT ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE
+ CASE WHEN CHARACTER_MAXIMUM_LENGTH > 0 THEN '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS nvarchar(10)) + ')' WHEN CHARACTER_MAXIMUM_LENGTH = -1 THEN '(max)' ELSE '' END
+ CASE WHEN DATA_TYPE IN ('numeric', 'decimal') AND NUMERIC_PRECISION > 0 THEN '(' + CAST(NUMERIC_PRECISION AS nvarchar(10)) 
    + CASE WHEN NUMERIC_SCALE > 0 THEN ',' + CAST(NUMERIC_SCALE AS NVARCHAR(10)) ELSE '' END
 + ')' ELSE '' END DATA_TYPE
INTO #Columns
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.TABLE_NAME LIKE '#Data%'
ORDER BY C.ORDINAL_POSITION

DECLARE @selectList nvarchar(max), @columnNames nvarchar(max)

SELECT @selectList = ISNULL(@selectList + ',', '') + 'CAST(' + QUOTENAME(COLUMN_NAME) + ' AS nvarchar(max)) ' + QUOTENAME(COLUMN_NAME),
    @columnNames = ISNULL(@columnNames + ',', '') + QUOTENAME(COLUMN_NAME)
FROM #Columns

DECLARE @unpivot nvarchar(max)

SET @unpivot = '
    SELECT b.Column_Name, b.DataValue, c.Data_Type
    FROM
    (
        SELECT ' + @selectList + ' FROM #Data
    ) a
    UNPIVOT (DataValue FOR Column_Name IN (' + @columnNames + ')) b
    JOIN #Columns c ON c.Column_Name = b.Column_Name
'

EXEC (@unpivot)