SQL, How to Concatenate results?

Darknight picture Darknight · Aug 27, 2009 · Viewed 126.5k times · Source

I currently have a SQL query that returns a number of fields. I need one f the fields to be effectively a sub query sub that.

The Problem in detail:

If I have a table X with two columns, ModuleID and say ModuleValue, how can I write a SQL query to take the results and Concatenate it into one field:

EG Results returned from

 (SELECT ModuleValue FROM Table_X WHERE ModuleID=@ModuleID)

Value 1

Value 2

Value 3

...

I need to return the result thus (as a single row, unlike the above):

Value 1, Value 2, Value 3

Is there a simple Concatenation method that could be user?

EDIT:

DB is MS TSQL (2005)

Answer

LukeH picture LukeH · Aug 27, 2009

This one automatically excludes the trailing comma, unlike most of the other answers.

DECLARE @csv VARCHAR(1000)

SELECT @csv = COALESCE(@csv + ',', '') + ModuleValue
FROM Table_X
WHERE ModuleID = @ModuleID

(If the ModuleValue column isn't already a string type then you might need to cast it to a VARCHAR.)