Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在sql中从xml检索所有父元素的所有子元素_Sql_Sql Server_Xml_Tsql - Fatal编程技术网

如何在sql中从xml检索所有父元素的所有子元素

如何在sql中从xml检索所有父元素的所有子元素,sql,sql-server,xml,tsql,Sql,Sql Server,Xml,Tsql,我尝试了以下sql查询来检索所有父元素的所有子元素,只有我可以获取第一个子元素 parent | child --------|--------- joel | john joel | sara joel | ram sam | david sam | george sam | wilson 您需要在每个父节点的节点上使用交叉应用和.nodes(): select a.b.value('parent-name[1]','varchar(

我尝试了以下sql查询来检索所有父元素的所有子元素,只有我可以获取第一个子元素

parent  |  child
--------|---------
joel    |  john
joel    |  sara
joel    |  ram
sam     |  david
sam     |  george
sam     |  wilson

您需要在每个父节点的
节点上使用
交叉应用
.nodes()

select a.b.value('parent-name[1]','varchar(50)') as parent
      , a.b.value('child[1]' ,'varchar(50)') as child
from @myxml.nodes('people/parent')a(b)

这将返回所有父级及其所有子级。

技巧是迭代子级,然后上升一级并获取父级名称

SELECT
    a.b.value('(parent-name)[1]', 'varchar(50)') as parent, 
    XChild.value('.' ,'varchar(50)') as child
FROM
    @myxml.nodes('people/parent') AS a(b)
CROSS APPLY
    b.nodes('child') AS XTbl(XChild)    
试试这个

select a.b.value('(../parent-name)[1]','varchar(50)') as parent
  , a.b.value('(.)[1]' ,'varchar(50)') as child
from @myxml.nodes('people/parent/child')a(b)
select a.b.value('(../parent-name)[1]','varchar(50)') as parent
  , a.b.value('(.)[1]' ,'varchar(50)') as child
from @myxml.nodes('people/parent/child')a(b)
select 
tbl.col.value('parent::*/@parent-name', 'varchar(50)') AS ParentName,
tbl.col.value('@child', 'varchar(50)') AS ChildName
from @x.nodes('/people/parent/child') as tbl(col);