Search code examples
sqlsql-servert-sqllegacy

How to replace STRING_AGG and CONCAT in MS SQL Server 2008?


I use MS SQL Server 2008 and this server version doesn't support some helpful functions like CONCAT and STRING_AGG, but they are really needful in my work. What variants can I have for replacing those functions in MS SQL Server 2008?

IMPORTANT! I have no possibility to update Server to newer version.

Code for better understanding:

SELECT Pt.ImagePath, STRING_AGG(Pt.DamageData, '') DamageData 
FROM @PreTable AS Pt 
GROUP BY ImagePath 
ORDER BY DamageData

Solution

  • Try this:

    WITH DataSoruce AS
    (
        SELECT DISTINCT ImagePath
        FROM @PreTable
    )
    SELECT DS.ImagePath
          ,C.DamageData
    FROM DataSoruce DS
    CROSS APPLY
    (
        SELECT '' + Pt.DamageData
        FROM @PreTable P
        WHERE P.ImagePath = DS.ImagePath
        FOR XML PATH('')
    ) C (DamageData);