Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Concatenate ids into a specific order

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?

like image 726
Simon Foster Avatar asked Aug 29 '13 11:08

Simon Foster


People also ask

How do I concatenate multiple rows into a single string in SQL?

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.

How do I concatenate multiple columns in SQL?

To concatenate more than 2 fields with SQL, you can use CONCAT() or CONCAT_WS() function.


2 Answers

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, '');
like image 175
Gordon Linoff Avatar answered Nov 10 '22 23:11

Gordon Linoff


The solution:

    SELECT  (cast(ID as nvarchar(max)) + ', ')  AS [text()]
      FROM    dbo.property
  ORDER BY ID
    FOR XML PATH ('')
like image 22
Harold Sota Avatar answered Nov 10 '22 23:11

Harold Sota