Click here to Skip to main content
15,890,741 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a one table returned from a query that looks something like this:-

EmpName
101
102
103
104
105
106
107

and I want all the Data to stack up like this
101 102 103 104 105 106 107

Note:-The number of records under 'EmpName' is not fixed so in case we have 100 records then it will show the output as pivot up to 100 Columns.
Posted

Assuming the fields are varchar, you can write the following code

SQL
DECLARE @ListEmp VARCHAR(MAX)
SELECT @ListEmp = COALESCE(@ListEmp+',' ,'') + EmpName FROM table_name
SELECT @ListEmp


if the fields are numeric, then convert the EmpName to varchar and then append the same..
 
Share this answer
 
Comments
Dharmenrda Kumar Singh 27-Jan-12 2:01am    
Here with this solution i am getting the result on a single column seperated by comma but i need every row as column.
SQL
DECLARE @EmpName AS TABLE (EmpId Bigint)
DECLARE @Cols AS NVARCHAR(MAX)
INSERT INTO @EmpName
SELECT 101 Union
SELECT 102 Union
SELECT 103 Union
SELECT 104 Union
SELECT 105 Union
SELECT 106 Union
SELECT 107 Union
SELECT 108

SET @Cols =''

SELECT @Cols = @Cols  + CAST(EmpId AS NVARCHAR(MAX)) + ' As [' + CAST(EmpId AS NVARCHAR(MAX))   + '],'
 FROM @EmpName

SET @Cols = 'SELECT ' +  SUBSTRING(@Cols , 1 , LEN(@Cols) - 1 )

EXEC sp_ExecuteSQL @Cols
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900