Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using COALESCE function to make values separated with commas

Tags:

sql-server

I have a table (EMP) I know that using the COALESCE function we can get the values of any column in this way

23,23,45,34  SELECT OfferID  FROM Emp where EmpID= 23 

but I am not getting the syntax to achieve this

Any help would be great, to resolve this issue.

like image 742
happysmile Avatar asked Jan 02 '12 12:01

happysmile


People also ask

How do I get 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.

How do you use coalesce function?

The SQL COALESCE function can be syntactically represented using the CASE expression. For example, as we know, the Coalesce function returns the first non-NULL values. SELECT COALESCE (expression1, expression2, expression3) FROM TABLENAME; The above Coalesce SQL statement can be rewritten using the CASE statement.


2 Answers

DECLARE @List VARCHAR(8000)  SELECT @List = COALESCE(@List + ',', '') + CAST(OfferID AS VARCHAR) FROM   Emp WHERE  EmpID = 23  SELECT @List  

This approach to aggregate concatenation is not guaranteed to work. If you are on at least SQL Server 2005 XML PATH or CLR aggregates are preferred.

The definitive article on the subject is Concatenating Row Values in Transact-SQL

like image 171
Martin Smith Avatar answered Sep 24 '22 06:09

Martin Smith


Description

I have done this using COALESCE in the past too, but i suggest another approach because you dont need a variable. Use the T-SQL function STUFF to get this done.

Sample

SELECT STUFF((     select ','+ cast(OfferID as nvarchar(255))      from Emp b     WHERE a.EmpID= b.EmpID     FOR XML PATH('')     ),1,1,'') AS COLUMN2 FROM Emp a GROUP BY a.EmpID 

More Information

STUFF (Transact-SQL)

like image 20
dknaack Avatar answered Sep 23 '22 06:09

dknaack