Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Numeric conversion error when aggregating strings with FOR XML PATH

I have a problem with a stuff query

I’ve table Bool_Eggs

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading