Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate Fields in Order - SQL Server

Tags:

sql

sql-server

I have a table consisting of 5 integer ids, and would like to add a column which takes these ids, orders them and concatenates them in some fashion similar to below.

id1       id2       id3      id4       id5      new_col
364       53        468      184       469      /53/184/364/468/469/
48        47        49       364       266      /47/48/49/266/364/

Is there a function which will make performing the ordering quicker and easier? God forbid if I have to code up the ordering by hand.

like image 408
cmcsorley17 Avatar asked Apr 26 '26 10:04

cmcsorley17


1 Answers

You could also use XML PATH (Online Demo)

SELECT id1,
       id2,
       id3,
       id4,
       id5,
       new_col = CONCAT('/', ids)
FROM   YourTable
       CROSS APPLY (SELECT CONCAT(id, '/')
                    FROM   (VALUES (id1),
                                   (id2),
                                   (id3),
                                   (id4),
                                   (id5)) V(id)
                    ORDER  BY id
                    FOR XML PATH('')) C(ids) 
like image 127
Martin Smith Avatar answered Apr 29 '26 02:04

Martin Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!