T-SQL - Parse Item Child是表中的XML

时间:2018-01-12 10:56:04

标签: xml tsql parsing

我有这张桌子

DECLARE @tbl TABLE 
             (
                [ItemId] NVARCHAR(250),
                [Quantity] DECIMAL(18, 2),
                xmlData XML
             );

INSERT INTO @tbl 
VALUES ('Item1', 3, '<record>  <memberList>    <itemMember>      <quantity>3.0</quantity>      <item internalId="553">             </item>         </itemMember>    <itemMember>      <quantity>2.0</quantity>      <item internalId="554">         </item>       </itemMember> </memberList></record>'),
       ('Item2', 5, '<record>  <memberList>    <itemMember>      <quantity>4.0</quantity>      <item internalId="53">           </item>        </itemMember>    <itemMember>      <quantity>6.0</quantity>      <item internalId="54">             </item>         </itemMember>    </memberList></record>')

我尝试解析XML以获取表中的Item Child。

我的预期结果:

DECLARE @Result TABLE 
                (
                    [ItemId] NVARCHAR(250),
                    [Quantity] DECIMAL(18, 2),
                    [ItemChild] NVARCHAR(250),
                    [QtyChild] NVARCHAR(250)
                );

INSERT INTO @tbl 
VALUES ('Item1', 3, '553', 3), ('Item1', 3, '554', 2),
       ('Item2', 5, '53', 4), ('Item2', 5, '54', 6)

请帮帮我。感谢。

1 个答案:

答案 0 :(得分:1)

试试这个:

INSERT INTO @Result(ItemId, Quantity, ItemChild, QtyChild)
    SELECT
        t.ItemId,
        t.Quantity,
        xc.value('(item/@internalId)[1]', 'NVARCHAR(250)'),
        xc.value('(quantity)[1]', 'NVARCHAR(250)')
    FROM
        @tbl t
    CROSS APPLY
        t.xmlData.nodes('/record/memberList/itemMember') AS XT(XC)

但我也建议使用最合适的数据类型为您的列ItemChildQtyChild - 那些是< / strong>数字,因此您不应该将它们存储为NVARCHAR(250) - INT使用ItemChildDECIMAL(18,2)使用QtyChild

DECLARE @Result TABLE 
                (
                    [ItemId] NVARCHAR(250),
                    [Quantity] DECIMAL(18, 2),
                    [ItemChild] INT,
                    [QtyChild] DECIMAL(18, 2)
                );

INSERT INTO @Result(ItemId, Quantity, ItemChild, QtyChild)
    SELECT
        t.ItemId,
        t.Quantity,
        xc.value('(item/@internalId)[1]', 'INT'),
        xc.value('(quantity)[1]', 'DECIMAL(18, 2)')
    FROM
        @tbl t
    CROSS APPLY
        t.xmlData.nodes('/record/memberList/itemMember') AS XT(XC)