STRING_AGG replacement in SQL Server 2016

Viewed 18057

I would like to aggregate single column values with an separator in between and with some prefix. Below is the code tried which works.

SELECT concat('TNB/IAG/',STRING_AGG(WF_ValStr, '/')) AS Result
    FROM wfattrdata where wf_id=35262472 and  WF_AttrID in (28,29,30,31,33);

I could get the below expected result in latest MSSql versions.

TNB/IAG/1/2/3/4/5

How to replace the above query to make it work in SQL Server 2016?

1 Answers

Check the below STUFF,XML code -

SELECT DISTINCT CONCAT('TNB/IAG/',T1.results) AS EXPECTED_RESULT FROM
(
select REPLACE(STUFF(CAST((
                    SELECT   ' /' +CAST(c.WF_ValStr AS VARCHAR(MAX))
                    FROM (  
                            SELECT distinct WF_ValStr
                            FROM wfattrdata
                        ) c
                    FOR XML PATH(''), TYPE) AS VARCHAR(MAX)), 1, 2, ''),' ','') AS results
                    from wfattrdata t) T1;
Related