Here are my tables:
-----------------------------------------
Hotels
-----------------------------------------
HotelID | HotelName
-----------------------------------------
-----------------------------------------
HotelImages
-----------------------------------------
HotelImageID | HotelID | Filename
-----------------------------------------
I’d like to create a SELECT statement that will return the data like so:
HotelID | HotelName | Images
-----------------------------------------
1 | Hotel1 | Image1,Image2,Image3
2 | Hotel2 | Image4,Image5,Image6
How can I modify my query to do this? I have:
SELECT H.HotelID, H.HotelName, '' AS Images
FROM Hotels H
I know I can use COALESCE to create a comma-delimited list:
DECLARE @Images varchar(500)
SELECT @Images = COALESCE(@Images + ',', '') + CAST(Filename AS varchar(100)) FROM HotelImages WHERE HotelID = 1
SELECT @Images
But I don’t know how to integrate that into my current query so that the list can be returned with the rest of the hotel data.
I should mention I’m using SQL Server 2000.
Since this is SQL 2000 you options are somewhat limited. You can’t use FOR XML PATH or recursive CTEs
Also the COALESCE trick only works for stuffing a comma delimited list for single hotel. Not all of them.
Honestly you’re better off doing this in the client. But if that can’t be done (certain Report Apps that-which-must-not-be-named come to mind) you can do the following.
Note the number of times the loop process is equal to maximum number of files associated with a hotel. This is much better than setting up a loop for each hotel (e.g. calling a UDF from the select clause).