SQL Server FOR XML Path make repeating nodes

前端 未结 5 1733
[愿得一人]
[愿得一人] 2020-12-01 22:05

I\'d like to generate the following output using SQL Server 2012:


  1
  2
  3<         


        
5条回答
  •  庸人自扰
    2020-12-01 22:39

    A couple notes here: If you use FOR XML EXPLICIT, you can't use WITH XMLNAMESPACES (a requirement I didn't mention, so I'm still leaving the accepted answer). While Iheria's answer was also very helpful, there's another simpler possibility I've since realized:

    SELECT CONVERT(XML, '' + t.col1 
               + '' + t.col2 
               + '' + t.col3 + '')
    FROM tbl t
    FOR XML PATH('parent'), TYPE
    

    I think this is probably the easiest and most performant way (I haven't benchmarked it, but I can't imagine using UNPIVOT would be faster and, if anything, the multiple SELECT option likely is refactored to this by the engine anyway).

提交回复
热议问题