SQL列到行

时间:2017-01-23 13:57:53

标签: sql sql-server-2008 tsql unpivot

从我的数据库表(Customer)中我需要选择一条记录并通过将列交换为行来显示结果。

EG: 实际结果

| ID | Name | Age |
| 1  | Tom  | 25  |

预期产出

| Name | Value|
| ID   | 1    |
| Name | Tom  |
| Age  | 25   |

其他详情:

  1. 客户表在不同数据库中具有不同数量的列
  2. 我需要在一个函数内执行此操作(所以我不能使用动态查询,UNPIVOT)
  3. 请建议我。

1 个答案:

答案 0 :(得分:1)

这使用CROSS APPLY和VALUES来执行unpivot

--Set up test data
CREATE TABLE dbo.TEST(ID INT IDENTITY (1,1),Name VARCHAR(20),Age TINYINT)

INSERT INTO  dbo.TEST VALUES
('Shaggy',32)
,('Fred',28)
,('Velma',26)
,('Scooby',7)



DECLARE @table VARCHAR(255) = 'Test'
DECLARE @schema VARCHAR(255) = 'dbo'
DECLARE @ID INT = 2

--Create a VALUES script for the desired table
DECLARE @col VARCHAR(1000)
SELECT
    @col = COALESCE(@col,'') + '(''' + c.name + ''' ,CAST(A.[' + c.name + '] AS VARCHAR(20))),' 
FROM
    sys.objects o
        INNER JOIN sys.columns c
            ON
            o.object_id = c.object_id
WHERE
    o.name = @table
    AND
    SCHEMA_NAME(o.schema_id) = @schema
ORDER BY
    c.column_id

--Remove trailing ,
SET @col = LEFT(@col,LEN(@col)-1)

--Build Script for unpivoting data.
DECLARE @str VARCHAR(2000) = '
SELECT
    CAST(C.Col AS VARCHAR(20)) AS [Name]
    ,CAST(C.Val AS VARCHAR(20)) AS [Value]
FROM
    [' + @schema + '].[' + @table + '] A
        CROSS APPLY (VALUES ' + @col + ') C(Col,Val)
WHERE
    A.ID = ''' + CAST(@ID AS VARCHAR(8)) + ''''

--Run Script
EXEC (@str)