XML返回太多行

时间:2017-10-28 14:27:45

标签: sql-server xml xquery

从下面的查询中,当我希望只获得两行时,我将返回7行。 我做错了什么?

 go
    declare @xml xml =
    '<people>
      <person ID="18" DOB="03 Apr 1955">
        <name>
          <FirstName>Walter</FirstName>
          <LastName>Thrip</LastName>
        </name>
        <Sex>M</Sex>
         <Sex>X</Sex>
        <title>Sir</title>
      </person>
      <person ID="19" DOB="01 Jan 2010">
        <name>
          <FirstName>john</FirstName>
          <LastName>smith</LastName>
        </name>
        <Sex>m</Sex>
        <DOD>20 Jan 2014</DOD>
      </person>
    </people>'
    select  
          n.value('../@ID','int') as ID
          ,n.value('@DOB','datetime') as DOB
          ,n.value('FirstName[1]','varchar(20)') as FirstName
          ,n.value('LastName[1]','varchar(20)') as LastName
          ,n.value('../Sex[1]', 'char(1)') as Sex
          ,n.value('../DOD[1]', 'datetime') as DOD
          ,n.value('../Title[1]', 'varchar(10)') as Title
    from @xml.nodes('(/people/person/*)') as a(n)

1 个答案:

答案 0 :(得分:3)

那是因为你在person 级别的子级上粉碎了XML,甚至还有7个。你应该改为person元素:

select  
      n.value('@ID','int') as ID
      ,n.value('@DOB','datetime') as DOB
      ,n.value('(name/FirstName)[1]','varchar(20)') as FirstName
      ,n.value('(name/LastName)[1]','varchar(20)') as LastName
      ,n.value('Sex[1]', 'char(1)') as Sex
      ,n.value('DOD[1]', 'datetime') as DOD
      ,n.value('Title[1]', 'varchar(10)') as Title
from @xml.nodes('/people/person') as a(n)

<强> rextester demo