shred xml具有可变数量的节点

时间:2010-04-12 13:13:25

标签: sql-server-2005 xquery

我有一个xml列,其中包含如下数据:

<AuthorList CompleteYN="Y">
<Author ValidYN="Y">
<LastName>Alió</LastName>
<ForeName>J L</ForeName>
<Initials>JL</Initials>
</Author>
<Author ValidYN="Y">
<LastName>Ortiz</LastName>
<ForeName>D</ForeName>
<Initials>D</Initials>
</Author>
<Author ValidYN="Y">
<LastName>Muftuoglu</LastName>
<ForeName>O</ForeName>
<Initials>O</Initials>
</Author>
<Author ValidYN="Y">
<LastName>Garcia</LastName>
<ForeName>M J</ForeName>
<Initials>MJ</Initials>
</Author>
</AuthorList>

作者的数量是可变的。提取第一作者等我没有问题:

SELECT
 ID,
 AuthorList.value('(Author/ForeName)[1]', 'varchar(max)') as ForeName,
 AuthorList.value('(Author/LastName)[1]', 'varchar(max)') as LastName,
 AuthorList.value('(Author/Initials)[1]', 'varchar(max)') as Initials
FROM   
      XMLs CROSS APPLY 
      xml.nodes('//AuthorList') AS AuthorList(AuthorList)

我很好奇我如何能够“动态地”实现这样的目标:

1 JLAlióJL 1 D Ortiz D. 1 O Muftuoglu O. 1 M J Garcia MJ

谢谢!

1 个答案:

答案 0 :(得分:0)

这似乎可以完成这项工作:

select 
    AuthorList.value('(ForeName/text())[1]', 'varchar(max)') as ForeName,
    AuthorList.value('(LastName/text())[1]', 'varchar(max)') as LastName,
    AuthorList.value('(Initials/text())[1]', 'varchar(max)') as Initials
from 
    XMLs CROSS APPLY 
      xml.nodes('//AuthorList/Author') AS AuthorList(AuthorList)