Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output a comma separated list in T-SQL

I have a table with phone numbers in it. Instead of spitting out a single row for each number I want to return a comma separated list of phone numbers. What's the easiest way to do this in sql? A while loop?

like image 933
Micah Avatar asked May 13 '11 18:05

Micah


People also ask

How do I display comma separated values in SQL?

In order to fetch the comma separated (delimited) values from the Stored Procedure, you need to make use of a variable with data type and size same as the Output parameter and pass it as Output parameter using OUTPUT keyword.


2 Answers

Some of those answers are overly complicated with coalesce and more complex XML queries. I use this all the time:

select @Phones=(
  Select PhoneColumn+','
  From TableName
  For XML Path(''))
-- Remove trailing comma if necessary
select @Phones=left(@Phones,len(@Phones)-1)
like image 138
Brent D Avatar answered Nov 07 '22 22:11

Brent D


You could create a UDF that would do something like this

CREATE FUNCTION dbo.GetBirthdays(@UserId INT)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @combined VARCHAR(MAX)
SELECT  @combined = COALESCE(@combined + ', ' + colName + ', colName)
FROM    YourTable
WHERE UserId = @UserId
ORDER BY ColName

END

Basically this just pulls all of the values into a simple list.

like image 34
Mitchel Sellers Avatar answered Nov 07 '22 21:11

Mitchel Sellers