I have the following query which works great, it puts all my ids in a comma separated list.
DECLARE @tmp nvarchar(max)
SET @tmp = ''
SELECT @tmp = @tmp + cast(id as nvarchar(max)) + ', '
FROM dbo.property
I want to put my ids in alphabetical order but when I add order by p.Name it only gives my the top one result.
How can I adapt my query to accomplish this?
You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.
To concatenate more than 2 fields with SQL, you can use CONCAT() or CONCAT_WS() function.
This really doesn't work?
DECLARE @tmp nvarchar(max);
SET @tmp = '';
SELECT @tmp = @tmp + cast(id as nvarchar(max)) + ', '
FROM dbo.property p
order by p.name;
In any case, you can use this method:
select @tmp = stuff((select ', ', cast(id as nvarchar(max))
from db.property p
order by p.name
for xml path ('')
), 1, 2, '');
The solution:
SELECT (cast(ID as nvarchar(max)) + ', ') AS [text()]
FROM dbo.property
ORDER BY ID
FOR XML PATH ('')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With