0

I have a table as shown below :

                     TBLContact
-------------------------------------------------
BranchId  DepartmentId  DepartmentName   Phone No
-------------------------------------------------
 BID100    DTID001       Mechanical       123654

 BID100    DTID001       Mechanical       887744

 BID101    DTID002       Automobile       045167

 BID101    DTID002       Automobile       674632

I have to structure a query in a stored procedure in a way such that, on passsing 'BranchId' as a parameter to the query it would return the Department Phone No's of the corresponding 'BranchId' in a single row separated by a comma, although the 'Phone No' exists in two rows for a specific 'BranchId'. For Example; Consider passing the value 'BID100' as a parameter to the query/stored procedure, the query would return me a result as below:

BranchId DepartmentId  DepartmentName   PhoneNo
---------------------------------------------------
 BID100    DT001        Mechanical    123654,887744

PS: I am using SQL Server 2008.

Rohit Kiran
  • 436
  • 1
  • 5
  • 17

2 Answers2

0

Here an example shown via the XML data() command in MS SQL Server is:

select PhoneNo + ', ' as 'data()' 

from TBLContact where branch_id = BID100

for xml path('')
Ankur
  • 126
  • 9
0

Use this script as basis

declare @PhoneNo VARCHAR(8000) 

select @PhoneNo = COALESCE(@PhoneNo+ ', ', '') + PhoneNo
from table
where BranchId = 'BID100'

select top 1  BranchId,  DepartmentId,  DepartmentName, @PhoneNo
from table
where BranchId = 'BID100'
Alex
  • 1,186
  • 10
  • 12