如何使用SQL Server从xml中获取子项列表中的父项值?

时间:2014-07-11 10:10:34

标签: sql-server xml

我有一个xml,其中有多个块,如下所示。

declare @Query as xml,
@poxmldoc INT

set @Query='<ProductionOrder><Header><MessageID>00000005</MessageID></Header><Body>ProductionOrderDetails>Workorder_ID>100</Workorder_ID<Item_ID>4010124</Item_ID<Publisheddata></Publisheddata><BOM><Position>1</Position><Item_ID>111</Item_ID><BOM_Qty>100</BOM_Qty><UoM>Liters</UoM>
</BOM><BOM><Position>2</Position><Item_ID>222</Item_ID><BOM_Qty>101</BOM_Qty><UoM>Kilograms</UoM></BOM><BOM><Position>3</Position><Item_ID>333</Item_ID><BOM_Qty>102</BOM_Qty><UoM>Kilograms</UoM></BOM></ProductionOrderDetails><ProductionOrderDetails><Workorder_ID>101</Workorder_ID><Item_ID>4010124</Item_ID><Publisheddata></Publisheddata><BOM><Position>1</Position><Item_ID>111</Item_ID><BOM_Qty>103</BOM_Qty><UoM>Liters</UoM></BOM><BOM><Position>2</Position><Item_ID>222</Item_ID><BOM_Qty>104</BOM_Qty><UoM>Kilograms</UoM></BOM><BOM><Position>3</Position><Item_ID>333</Item_ID><BOM_Qty>105</BOM_Qty><UoM>Kilograms</UoM></BOM></ProductionOrderDetails></Body></ProductionOrder>'

执行此查询时

EXEC SP_XML_PREPAREDOCUMENT @poxmldoc OUTPUT, @Query

SELECT * 
FROM OPENXML(@poxmldoc, '/ProductionOrder/Body/ProductionOrderDetails/BOM',2)
     WITH (Position INT 'Position',
           Item_ID NVARCHAR(40) 'Item_ID',
           BOM_Qty FLOAT 'BOM_Qty',
           UoM NVARCHAR(40) 'UoM')

我得到了这个输出:

Position    Item_ID BOM_Qty UoM
------------------------------------
1            111    100     Liters
2            222    101     Kilograms
3            333    102     Kilograms
1            111    103     Liters
2            222    104     Kilograms
3            333    105     Kilograms

如何获得<Workorder_ID>标记值以及此结果。

像这样:

Position    Item_ID BOM_Qty UoM        Wo_Id
---------------------------------------------
1            111    100     Liters     100
2            222    101     Kilograms  100
3            333    102     Kilograms  100
1            111    103     Liters     101  
2            222    104     Kilograms  101
3            333    105     Kilograms  101

2 个答案:

答案 0 :(得分:0)

使用XPath / XQuery。即:

select  
    p.value('Position[1]','int'),
    p.value('Item_ID[1]','int'),
    p.value('BOM_Qty[1]','int'),
    p.value('UoM[1]','varchar(20)'),
    p.value('../Workorder_ID[1]','int')

from 
    @query.nodes('/ProductionOrder/Body/ProductionOrderDetails/BOM') x(p)

答案 1 :(得分:0)

鉴于您的@Query XML变量,您可以使用此原生XQuery来获取您正在寻找的内容:

SELECT
    POSITION = XC.value('(Position)[1]', 'int'),
    ItemID = XC.value('(Item_ID)[1]', 'int'),
    BomQty = XC.value('(BOM_Qty)[1]', 'int'),
    UnitOfMeasure = XC.value('(UoM)[1]', 'varchar(50)'),
    Workorder_ID = XC.value('(../Workorder_ID)[1]', 'int')
FROM
    @Query.nodes('/ProductionOrder/Body/ProductionOrderDetails/BOM') AS XT(XC)

通过指定(../Workorder_ID) XPath,您基本上可以访问相关<BOM>元素的父元素。