Wednesday, April 16, 2008

Covert Row To Column In SQL Server 2005

Let us suppose that you have a table like below

col1 | col2 | col3

--------*---------*----------

Value 1 | Value 2 | Value 3

And change it to one that looks like this:

Name | Value

-----*---------

col1 | Value 1

-----*---------

col2 | Value 2

-----*---------

col3 | Value 3





DECLARE @Table Table

(col1 varchar(10),

col2 varchar(10),

col3 varchar(10))

INSERT INTO @TABLE VALUES ('Value 1', 'Value 2', 'Value 3')

INSERT INTO @TABLE VALUES ('Value 4', 'Value 5', 'Value 6')

INSERT INTO @TABLE VALUES ('Value 7', 'Value 8', 'Value 9')



SELECT col, colval

FROM

(SELECT col1, col2, col3

FROM @TABLE) p

UNPIVOT

(ColVal FOR Col IN

(col1, col2, col3)

)AS unpvt

2 comments:

skyemarielopez said...

Thank you so much for providing this informative article. An excellent read, please keep us informed like this. Kudos!

www.n8fan.net

Cindy Dy said...

Very interesting story,. I didn't find it boring to read. In fact, I really had a fun reading your post. Thanks.

Shella
www.gofastek.com