TSQL XML逗号分隔列表

时间:2015-06-19 18:31:12

标签: sql-server tsql

我正在尝试使用逗号分隔字段。该结构看起来非常类似于下面的结构。我想为下面的所有节点获取逗号分隔列表。

DECLARE @Test XML = '

    <Order id="orderId">
      <Products>
        <Product>1</Product>
        <Product>2</Product>
        <Product>3</Product>
        <Product>4</Product>
        <Product>5</Product>
      </Products>
      <Address street="1234 City World" zip="12345" city="City" state="FL"></Address>
</Order>'

SELECT 
  @Test.value('(/Order/@id)[1]', 'NVARCHAR(1000)') AS OrderId,
  @Test.value('(/Order/Address/@street)[1]', 'NVARCHAR(1000)') AS Street,
  @Test.value('(/Order/Address/@city)[1]', 'NVARCHAR(1000)') AS City,
  @Test.value('(/Order/Address/@state)[1]', 'NVARCHAR(1000)') AS State,
  @Test.value('(/Order/Address/@zip)[1]', 'NVARCHAR(1000)') AS Zip,
  @Test.query('Order/Products/Product/text()') AS prods 

我得到的那些:

OrderId的“orderid” “1234城市世界”为街 城市的“城市” 国家的“FL” 邮编“1245”。 “12345”为Prods。

我想获得“1,2,3,4,5”的产品。

感谢,

1 个答案:

答案 0 :(得分:1)

通过使用此功能,我能够达到您期望的结果:

SELECT  @Test.value('(/Order/@id)[1]', 'NVARCHAR(1000)') AS OrderId ,
        @Test.value('(/Order/Address/@street)[1]', 'NVARCHAR(1000)') AS Street ,
        @Test.value('(/Order/Address/@city)[1]', 'NVARCHAR(1000)') AS City ,
        @Test.value('(/Order/Address/@state)[1]', 'NVARCHAR(1000)') AS State ,
        @Test.value('(/Order/Address/@zip)[1]', 'NVARCHAR(1000)') AS Zip ,
        ( SELECT    
            STUFF(( SELECT  ',' + Prods.Prod.value('text()[1]','varchar(max)')
                    FROM    @Test.nodes('/Order/Products/Product') AS Prods ( Prod )
                    FOR XML PATH('')
            ), 1, 1, '')
        ) prods

这有点令人困惑,但我所做的就是选择Products节点并将其转换为&#34;表&#34;然后我使用FOR XMLSTUFF来将它们连接在同一行。

STUFF功能不适用于旧版本的SQL Server,因此您可能需要调整此解决方案,如果需要,可以尝试this answer

我希望它有所帮助。