Firstly, the SQL you have won't generate the error you state you get. If you try running the above you get the following error:
Column name 'Data()' contains an invalid XML identifier as required by FOR XML; '('(0x0028) is the first character at fault.
This is because XML nodes can't have parenthesis (()
) in their name.
It sounds, like, however, that you shouldn't even be aliasing as you want a concatenated list of all your ID
's from your table. If so, then your query should actually look like this:
SELECT STUFF((SELECT CONCAT(', ',ID) --I assume ID could be a non-string type
FROM Test_schema.Table_name
FOR XML PATH(''),TYPE).value('(./text())[1]','nvarchar(MAX)'),1,2,N'');
If, however, you're on a more recent version of SQL Server, just us STRING_AGG
:
SELECT STRING_AGG(ID,', ')
FROM Test_schema.Table_name;