1

I have a table as shown below.My question is:How can I convert columns into rows? I'm using Microsoft SQL Server

   sip_RECno  user1     user2    user3     user4       

   1          ram       ravi     sam       raj

i need op like below

 user
 ram
 ravi
 sam
 raj

how to do it? thanks

3

2 Answers 2

8

Your Data

DECLARE @TABLE TABLE 
(sip_RECno INT,user1 VARCHAR(10),user2 VARCHAR(10)
,user3 VARCHAR(10),user4 VARCHAR(10))      

INSERT INTO @TABLE VALUES
(1,'ram','ravi','sam','raj')

Query

;WITH CTE
AS
  (
  SELECT * FROM (
  SELECT user1 ,user2 ,user3 , user4 FROM @TABLE) T
  UNPIVOT ( Value FOR N IN (user1 ,user2 ,user3 , user4))P
  )
 SELECT Value AS Users
 FROM CTE

Result Set

╔═══════╗
║ Users ║
╠═══════╣
║ ram   ║
║ ravi  ║
║ sam   ║
║ raj   ║
╚═══════╝
Sign up to request clarification or add additional context in comments.

2 Comments

how to do for dynamic columns ?
@Happy it will be another long answer to explain this have a look here scroll down to the middle of this page to see how dynamicaly pivot/unpivot data codeproject.com/Tips/516896/…
5

You can simply UNPIVOT()

select [user] from table_name unpivot 
      (
       [user]
       for [userid] in ([user1], [user2], [user3], [user4]) 
      )unpvt

Demo

2 Comments

how to do for dynamic columns ?
by using Dynamic SQL and ` FOR XML PATH`

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.