Saturday, May 28, 2011

Converting rows into Columns using SQLServer database

Fetching rows values into comma separated column value.
Step 1:
Create a table named EmpTable with one field named EName as follows
Create TABLE EmpTable (EName Varchar(100) )
Step 2:
Insert some Values into the table as follows
INSERT INTO EmpTable VALUES ('Ajay')
INSERT INTO EmpTable VALUES ('Bhanu')
INSERT INTO EmpTable VALUES ('Chandu')
Step 3:
Use Stuff function and create comma separated values by writing query in the SQLServer database

SELECT STUFF(( SELECT ', ' + [Name] FROM (SELECT [EName] FROM EmpTable) AS T FOR XML PATH('') ) ,1,1,'') AS [Name]

The output for the above query is as follows:

Name
------------------------------------
Ajay, Bhanu, Chandu