DECLARE @Test TABLE (ID INT NOT NULL, XmlContent XML)
INSERT INTO @Test VALUES (1,
'<location>
<locationName>Loc1</locationName>
<locationInchargeName>User1</locationInchargeName>
</location>
<location>
<locationName>Loc2</locationName>
<locationInchargeName>User2</locationInchargeName>
<locationInchargeName>User3</locationInchargeName>
</location>')
SELECT ID, E.P.value('locationName[1]','varchar(200)') as locationName,
E.P.value('locationInchargeName[1]','varchar(200)') AS locationInchargeName
FROM @Test
CROSS APPLY XmlContent.nodes('location') as E(P)
这为我提供了每个位置名称的输出以及第一个位置incharge名称。
locationName locationInchargeName
------------- ---------------------
Loc1 User1
Loc2 User2
如何获取所有locationInchargeNames的名称及其位置名称?像这样:
locationName locationInchargeName
------------- ---------------------
Loc1 User1
Loc2 User2
Loc2 User3
非常感谢任何帮助。
答案 0 :(得分:0)
试试这个:
SELECT
ID,
XTbl1.Loc.value('locationName[1]','varchar(200)') as locationName,
XTbl2.InCharge.value('.','varchar(200)') AS locationInchargeName
FROM @Test
CROSS APPLY XmlContent.nodes('location') as XTbl1(Loc)
CROSS APPLY XTbl1.Loc.nodes('locationInchargeName') as XTbl2(InCharge)