开发者

Get a delimited string from XML with SQL Server 2005 XQuery

开发者 https://www.devze.com 2023-04-12 01:48 出处:网络
I cannot seem to get a [comma-]delimited string out of an XML doc using just SQL Server 2005 XQuery.

I cannot seem to get a [comma-]delimited string out of an XML doc using just SQL Server 2005 XQuery.

I have:

<AAA>
  <Name>Name_A</Name>
  <Value>Val_A</Value>
</AAA>
<AAA>
  <Name>Name_B</Name>
  <Value>Val_B</Value>
</AAA>
<AAA>
  <Name>Name_C</Name>
  <Value>Val_开发者_JS百科C</Value>
</AAA>
... (etc.)

... and would like to get Val_A,Val_B,Val_C... - a comma-delimited string.

I can convert to a table then back to string with FOR XML, but thought there is a direct way.

Thank you.


How about this - this will work for any number of <AAA> nodes in an XML variable:

DECLARE @Input XML = '<AAA>
  <Name>Name_A</Name>
  <Value>Val_A</Value>
</AAA>
<AAA>
  <Name>Name_B</Name>
  <Value>Val_B</Value>
</AAA>
<AAA>
  <Name>Name_C</Name>
  <Value>Val_C</Value>
</AAA>'

SELECT
    STUFF(
    (SELECT 
        ',' + AAA.value('(Value)[1]', 'varchar(20)')
     FROM
        @Input.nodes('/AAA') AS Node(AAA)
     FOR XML PATH('')
    ), 1, 1, '')

Output is:

Val_A,Val_B,Val_C


declare @xml xml = '
<AAA>
  <Name>Name_A</Name>
  <Value>Val_A</Value>
</AAA>
<AAA>
  <Name>Name_B</Name>
  <Value>Val_B</Value>
</AAA>
<AAA>
  <Name>Name_C</Name>
  <Value>Val_C</Value>
</AAA>
'

select @xml.value('(/AAA[1]/Value)[1]', 'varchar(10)')+','+
       @xml.value('(/AAA[2]/Value)[1]', 'varchar(10)')+','+
       @xml.value('(/AAA[3]/Value)[1]', 'varchar(10)')


How about

string-join(/AAA/Value, ",")

(You might need to adapt the beginning of the Path expression depending on how you read your input)

0

精彩评论

暂无评论...
验证码 换一张
取 消