2017-10-27 14 views
0

XMLを持つMSSQLデータベースをクエリして解析しようとしています。ここMSSQL同じ兄弟を含むXMLの解析

はデータです:

ここ
<Root> 
<Relatives> 
<Relative> 
    <Relation>Father</Relation> 
    <BcAge>50</BcAge> 
    <BilatAge>0</BilatAge> 
    <OcAge>0</OcAge> 
</Relative> 
<Relative> 
    <Relation>Mother</Relation> 
    <BcAge>58</BcAge> 
    <BilatAge>0</BilatAge> 
    <OcAge>0</OcAge> 
</Relative> 

が望ましい結果

Relation BcAge BilatAge OcAge Relation BcAge BilatAge OcAge 
Father 50  0  0  Mother 58 0   0 

答えて

1

である私は、あなたが本当にあなたの結果サイド・バイ・サイドを取得したいことを、疑います ...これは有効な結果セットではなく、列名が重複しています。

あなたが本当にそれをあなたがこれを行う可能性があります。この方法が必要な場合:

DECLARE @xml XML= 
N'<Root> 
<Relatives> 
<Relative> 
    <Relation>Father</Relation> 
    <BcAge>50</BcAge> 
    <BilatAge>0</BilatAge> 
    <OcAge>0</OcAge> 
</Relative> 
<Relative> 
    <Relation>Mother</Relation> 
    <BcAge>58</BcAge> 
    <BilatAge>0</BilatAge> 
    <OcAge>0</OcAge> 
</Relative> 
</Relatives> 
</Root>'; 

クエリがXQuery-predicate

WITH Parents AS 
(
    SELECT @xml.query(N'/Root/Relatives/Relative[(Relation/text())[1]="Father"]') AS Father 
      ,@xml.query(N'/Root/Relatives/Relative[(Relation/text())[1]="Mother"]') AS Mother 
) 
SELECT 'Father' AS F_Relation 
     ,Father.value(N'(/Relative/BcAge)[1]',N'int') AS F_BcAge 
     ,Father.value(N'(/Relative/BilatAge)[1]',N'int') AS F_BilatAge 
     ,Father.value(N'(/Relative/OcAge)[1]',N'int') AS F_OcAge 
     ,'Mother' AS M_Relation 
     ,Mother.value(N'(/Relative/BcAge)[1]',N'int') AS M_BcAge 
     ,Mother.value(N'(/Relative/BilatAge)[1]',N'int') AS M_BilatAge 
     ,Mother.value(N'(/Relative/OcAge)[1]',N'int') AS M_OcAge 
FROM Parents; 

で父と母を取得するために、CTEを使用します。しかし、おそらくそれは、このですあなたは(<Relative>の任意のカウント)を探しています:

SELECT rel.value(N'(Relation/text())[1]',N'nvarchar(max)') AS Relation 
     ,rel.value(N'(BcAge/text())[1]',N'int') AS BcAge 
     ,rel.value(N'(BilatAge/text())[1]',N'int') AS BilatAge 
     ,rel.value(N'(OcAge/text())[1]',N'int') AS OcAge 
FROM @xml.nodes(N'/Root/Relatives/Relative') AS A(rel) 
関連する問題