Question : Return Multiple Rows as Delimited List

I have a DB we are using to track different jobs.  There is a table [Issues] that holds all info on the job, then there is another table [Inventory] that holds all inventory items.  [Inventory] table is setup like so:

id|task_id|name|quantity

and [Issues] like this:

task_id|title|etc...

Since there can be multiple inventory items used for each issue, [task_id] is linked to item in inventory table.  I would like to return [name] field for each inventory item associated with particular job, but I need them in a delimited list as one column in query like so:

task_id|title|parts
1|My Title|name1, name2, name3

Is there any way to do this in SQL view or do I need to create a temp table to hold this data then update the [parts] column myself?

Answer : Return Multiple Rows as Delimited List

CREATE FUNCTION dbo.MakeList(@task_id INT) RETURNS VARCHAR(1000) AS
BEGIN
  DECLARE @list VARCHAR(1000)
  SELECT @list = ISNULL(@list + ',', '') + [name] FROM [Inventory] WHERE task_id = @task_id
  RETURN @list
END

SELECT task_id, title, dbo.MakeList(task_id) AS parts FROM [Issues]
Random Solutions  
 
programming4us programming4us