handling multiple results from subquery

zephyr_hex (Megan)
zephyr_hex (Megan) used Ask the Experts™
i have a table with unique orderID.  i have another table with tech information, and this table also has orderID.  however, there can be multiple rows in the tech table per orderID.

is it possible to SELECT all of the tech names from the tech table as a string separated by commas?  so, if there are two techs for order X, the following would be returned:

Joe, Bob

select column1, column2, column3, (select techName from techTable where techTable.orderID = orderTable.orderID) from orderTable

i can't do the above because techName can have multiple results.  is it possible to format the multiple results to return 1 result from the subquery?

sql server 2005
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Something like that. It's using CTE in order to remove last comma
;with CTE(column1, column2, column3, CSVList)
	select o.column1, o.column2, o.column3, 
			select techName as [text()], ',' as [text()] 
			from techTable 
			where techTable.orderID = ¿.orderID
			for XML PATH('')
		) as CSVList
	from orderTable o
	column1, column2, column3,
		WHEN csvlist is null 
		THEN '' 
		ELSE SUBSTRING(csvlist,1,LEN(csvlist) - 1)

Open in new window

Top Expert 2010


thanks.  i was also able to achieve this using:

,(select techtable.techName + ',' from techtable where techtable.orderID = maintable.orderID for xml path('')) as techname

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial