TSQL Comma Separation

前端 未结 7 1902
夕颜
夕颜 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条回答
  •  -上瘾入骨i
    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 [], [], [etc...], (
        SELECT CAST([] AS VARCHAR(MAX)) + 
            CASE WHEN (ROW_NUMBER() OVER (ORDER BY []) = 1)
                THEN '' ELSE ',' END
            AS [text()]
        FROM []
        WHERE [] = []
        AND []
        ORDER BY []
        FOR XML PATH('')) AS []
    FROM []
    

    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.

提交回复
热议问题