0

I Have a table like this:

a  |  b  |  c
-------------
1  |  2  |  3

where the first row are column names. I want to swap entire table and converto to this:

col  |  val
-----------
a    |  1
b    |  2
c    |  3

How can I do this by Unpivot in T-SQL?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Hamed Zakery Miab
  • 738
  • 2
  • 12
  • 34

2 Answers2

1

Try this:

--Create YourTable
SELECT  1 AS a,
        2 AS b,
        3 AS c INTO YourTable

--Unpivot YourTable
SELECT  unpvt.Col,
        unpvt.Val
FROM YourTable
UNPIVOT 
    (Val for Col in (a,b,c)) unpvt
Stephan
  • 5,891
  • 1
  • 16
  • 24
1

If you have multiple data types, then you can cast the columns as NVARCHAR since most data types can be casted as NVARCHAR like so:

   --Create YourTable
SELECT  N'unicode text' AS a,
        CAST(23123123 AS BIGINT)AS b,
        CAST('20120101' AS DATE) AS c INTO YourTable

--Unpivot YourTable
SELECT  unpvt.Col,
        unpvt.Val
FROM 
--Cast each column as NVARCHAR
(
    SELECT  CAST(a AS NVARCHAR(MAX)) a,
            CAST(b AS NVARCHAR(MAX)) b,
            CAST(c AS nvarchar(MAX)) c
    FROM YourTable
) A
UNPIVOT 
    (Val for Col in (a,b,c)) unpvt

DROP TABLE YourTable
Stephan
  • 5,891
  • 1
  • 16
  • 24