如何在SQL Sproc中使用XPATH获取以下输出

时间:2011-07-14 00:47:18

标签: sql xpath

假设xml输入是

<Tasks>
 <Task Name="Add2">
   <Dependency Name="S1"/>
 </Task>
 <Task Name="Min2">
  <Dependency Name="Dev1"/>
  <Dependency Name="Extra"/>
  </Task>
<Tasks>

我希望结果为

Add2   S1
Min2   Dev1
Min2   Extra

如何在Sql Sproc中使用Xpath实现此目的

2 个答案:

答案 0 :(得分:1)

您之前的一些问题是关于SQL Server的......

declare @xml xml = '
<Tasks>
 <Task Name="Add2">
   <Dependency Name="S1"/>
 </Task>
 <Task Name="Min2">
  <Dependency Name="Dev1"/>
  <Dependency Name="Extra"/>
  </Task>
</Tasks>'


select T1.N.value('@Name', 'varchar(max)') as TaskName,
       T2.N.value('@Name', 'varchar(max)') as DependencyName
from @xml.nodes('/Tasks/Task') as T1(N)
  cross apply T1.N.nodes('Dependency') as T2(N)

答案 1 :(得分:0)

您在技术上需要使用xpath路径两次,因为您正在访问不同的节点。我会给你sql server方式:

declare @xml_content xml = '<Tasks>
 <Task Name="Add2">
   <Dependency Name="S1"/>
 </Task>
 <Task Name="Min2">
  <Dependency Name="Dev1"/>
  <Dependency Name="Extra"/>
  </Task>
<Tasks>'

with roots as (
select x.value('@Name','varchar(max)') task_name,x.query('.') deps
from @xml_content.nodes('Tasks/Task') a(x)
)

select r.task_name,x.value('@Name','varchar(max)') dependency_name
from roots r
cross apply roots.deps.nodes('/Task/Dependency') a(x)