Using SQL Server 10.0 and 10.5
I’m trying to fetch multiple rows into one row and comma seperate them in a SELECT statement
If I do this:
SELECT STUFF(CAST(rating AS VARCHAR),1,0,',')
FROM product_reviews
WHERE product_id = 8995
FOR XML PATH('')
I get the desired result except for the leading comma.
So I change the first line to attempt to remove the leading comma like so:
SELECT SUBSTRING(STUFF(CAST(rating AS VARCHAR),1,0,','),2,999)
FROM product_reviews
WHERE product_id = 8995
FOR XML PATH('')
This removes all the commas.
Next I try this:
SELECT SUBSTRING(ratings,2,999)
FROM (SELECT STUFF(CAST(rating AS VARCHAR),1,0,',') AS ratings
FROM product_reviews
WHERE product_id = 8995
FOR XML PATH('')) tmp
But that just gives me the error:
Msg 8155, Level 16, State 2, Line 5
No column name was specified for column 1 of 'tmp'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'ratings'.
I have used other names for column 1 with same error
I know I can create a procedure to do this, but that’s not what I need here.
Any help appreciated.
Thank you
How about