I have a problem with a stuff query
I’ve table Bool_Eggs
it is my select, what am I wrong do, please tell me
SELECT
STUFF((SELECT ',' + s.Quantity
FROM Book_Degree s
FOR XML PATH('')), 1, 1, '')
my Error
Error converting data type varchar to real.
>Solution :
Numeric data types have a higher precedence than varchar, so it’s trying to implicitly convert ',' to numeric. Instead you could use CAST to force Quantity to be varchar, but it’s probably easier to just use CONCAT on the whole thing.
SELECT STUFF((
SELECT CONCAT(',', s.Quantity)
FROM Book_Degree s
FOR XML PATH('')
), 1, LEN(','), '');
Note that in the event you are aggregating anything that might have characters that need to be escaped in XML, you need to change the code to
FOR XML PATH(''), TYPE
).value('text()[1]','nvarchar(max)'), 1, LEN(','), '');
And obviously in newer versions of SQL Server you can just use STRING_AGG
SELECT STRING_AGG(s.Quantity, ',')
FROM Book_Degree s;
