SQL Server -XML节点不返回多个记录

时间:2017-02-14 17:51:48

标签: sql sql-server xml tsql

我试图了解SQL,XML节点和Cross应用程序,我会认为以下代码将返回3行数据,但我只得到一行。我以为使用Cross apply将查询加入到自身中会为我解决这个问题。

有人可以告诉我我做错了什么吗?

提前致谢

DECLARE @XML AS XML;

SELECT @XML = ('<Deal deal_id="821">
  <Application_owner>me</Application_owner>
   <Deal_files>
    <File>file1.doc</File>
    <File>file2.pdf</File>
    <File>file3.xcl</File>
  </Deal_files>
</Deal>
')

select 
    t.n.value('@deal_id', 'int') as [ID],
    f.n.value('(File)[1]','varchar(50)') as [FILENAME]
from 
    @XML.nodes('Deal') t(n)
cross apply 
    t.n.nodes('Deal_files') f(n)

1 个答案:

答案 0 :(得分:5)

你很亲密

DECLARE @XML AS XML;

SELECT @XML = ('<Deal deal_id="821">
  <Application_owner>me</Application_owner>
   <Deal_files>
    <File>file1.doc</File>
    <File>file2.pdf</File>
    <File>file3.xcl</File>
  </Deal_files>
</Deal>
'
)

Select 
    ID = t.n.value('@deal_id', 'int'),
    FileName = f.n.value('(.)[1]','varchar(50)') 
From  
    @XML.nodes('Deal') t(n)
Cross Apply 
    t.n.nodes('Deal_files/*') f(n)

返回

ID  FileName
--------------
821 file1.doc
821 file2.pdf
821 file3.xcl