Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

Get comma separated result

1.18/5 (6 votes)
15 Nov 2007 1  
Create command for getting comma seperated value

Introduction

Here is some help for people who are awaiting for output from Sql server command described as below. As we are having one table named as MyTable in which we are having two columns named as Dept which contains name of all department within company and another column named as EmpName contains name of all the employess working in the company related to that department.

Now, with the store procedure we are getting all the department name in first column and in second column we are having all the employee names comma separated. So with the below code we will get the same out put.

Using the code

I have table name : MyTable.

Columns : Dept, EmpName

I have table output like below:

DeptEmpName
Software Emp1
Software Emp2
Software Emp3
Account Emp4
Account Emp5

And I want output as below.

DeptEmpName
Software Emp1, Emp2, Emp3
Account Emp4, Emp5


//
// Code is shown below
//
SET ANSI_WARNINGS OFF
Declare @ono varchar(50)
DECLARE My_Cursor CURSOR FOR
SELECT distinct Dept
FROM MyTable
drop table tmp
create table tmp(ono varchar(50),allname varchar(50))
OPEN My_Cursor
FETCH NEXT FROM My_Cursor into @ono
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @EmployeeList varchar(100)
set @EmployeeList = null
SELECT  @EmployeeList = COALESCE(@EmployeeList + ', ', '') + 
   CAST(EmpName AS varchar(5))
FROM MyTable where Dept = @ono
insert into tmp(ono,allname) values(@ono,@EmployeeList)
    FETCH NEXT FROM My_Cursor into @ono
END
CLOSE My_Cursor
DEALLOCATE My_Cursor
select * from tmp

Points of Interest

Change anything as per your requirement. Happy coding.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here