1.我有如下的XML数据,Child3可能有也可能没有Child4。如果Child4在那里,应该添加另一列。
<Parent name="ABC">
<Child name="123">
<Child1 text="child123" />
<Child1 text="Child345" />
<Child1 text="Status">
<Child2 text="Pending">
<Child3 text="Excise" />
<Child3 text="Financial" />
</Child2 >
<Child2 text="Over">
<Child3 text="A1111" />
</Child2 >
</Child1 >
</Child >
</Parent `>
我想要一个结果集,如:
ABC 123 child123 null null``
ABC 123 Child345 null null
ABC 123 Status Pending Excise
ABC 123 Status Pending Financial
ABC 123 Status Over A1111
我写了一个这样的查询:
SELECT Parent ,Child, Child1, Child2, Child3
FROM OPENXML(@hDoc, '/Parent /Child /Child1 /Child2 /Child3 ',2)
WITH
(
ReleaseInfo [varchar](max) '../../../../@name',
L1Data [varchar](max) '../../../@name',
L2Data [varchar](max) '../../@text',`
L3Data [varchar](max) '../@text',
L4Data [varchar](max) '@text')
我没有得到前两个记录。请建议。
答案 0 :(得分:1)
declare @XML xml = '
<Parent name="ABC">
<Child name="123">
<Child1 text="child123" />
<Child1 text="Child345" />
<Child1 text="Status">
<Child2 text="Pending">
<Child3 text="Excise" />
<Child3 text="Financial" />
</Child2>
<Child2 text="Over">
<Child3 text="A1111" />
</Child2>
</Child1>
</Child>
</Parent>'
select P.X.value('@name', 'varchar(max)') as Parent,
C.X.value('@name', 'varchar(max)') as Child,
C1.X.value('@text', 'varchar(max)') as Child1,
C2.X.value('@text', 'varchar(max)') as Child2,
C3.X.value('@text', 'varchar(max)') as Child3
from @xml.nodes('/Parent') as P(X)
outer apply P.X.nodes('Child') as C(X)
outer apply C.X.nodes('Child1') as C1(X)
outer apply C1.X.nodes('Child2') as C2(X)
outer apply C2.X.nodes('Child3') as C3(X)