TSQL Comma Separation

前端 未结 7 1900
夕颜
夕颜 2020-12-10 20:12

I\'m writing an export function, where I need to export contacts to Excel, and I\'ve run into a technical snag - or perhaps a gap in my SQL skills is closer to the truth. ;)

相关标签:
7条回答
  • 2020-12-10 21:10

    You can do it in a single query, though I don't know if the performance is good or bad.

    SELECT [<group field 1>], [<group field 2>], [etc...], (
        SELECT CAST([<field to list>] AS VARCHAR(MAX)) + 
            CASE WHEN (ROW_NUMBER() OVER (ORDER BY [<inner order-by REVERSED>]) = 1)
                THEN '' ELSE ',' END
            AS [text()]
        FROM [<inner table>]
        WHERE [<inner table join field>] = [<outer table join field>]
        AND [<inner conditions>]
        ORDER BY [<inner order-by>]
        FOR XML PATH('')) AS [<alias>]
    FROM [<outer table]
    WHERE [<outer conditions>]
    

    That CASE statement inside is just to remove the last comma from the list--you have to ORDER BY something for the inner query and then reverse that ORDER BY in the CASE statement.

    0 讨论(0)
提交回复
热议问题