循环 XML 数据并使用 SQL 存储过程插入到另一个表中

问题描述 投票:0回答:1

我有这个 XML:

<Root>
    <NEW_BATCH_NUM>A1234</NEW_BATCH_NUM>
    <NEW_LOCATION>US11</NEW_LOCATION>
    <TRANSACTION_DATE>11/8/2024 6:54:03 AM</TRANSACTION_DATE>
    <CHILD_BATCHES>
        <CHILDBATCH>
            <BATCH_NUM>C101</BATCH_NUM>
            <QTY>1500</QTY>
        </CHILDBATCH>
        <CHILDBATCH>
            <BATCH_NUM>C102</BATCH_NUM>
            <QTY>2000</QTY>
        </CHILDBATCH>
    </CHILD_BATCHES>
</Root>

需求基于

CHILDBATCH
节点,我需要使用SQL存储过程将数据插入到另一个表中。

预期结果是

NEW_BATCH_NUM   NEW_LOCATION    CHILD_BATCH_NUM   QTY
------------------------------------------------------
A1234               US11            C101         1500
A1234               US11            C102         2000 

请在此指导。

xml stored-procedures
1个回答
0
投票

此类操作不需要循环。它可以作为基于集合的操作来完成。

XQuery .nodes() 方法正在将 XML 转换为矩形/关系格式。

CROSS APPLY
正在模拟一对多关系。

SQL

DECLARE @parameter XML =
N'<Root>
    <NEW_BATCH_NUM>A1234</NEW_BATCH_NUM>
    <NEW_LOCATION>US11</NEW_LOCATION>
    <TRANSACTION_DATE>11/8/2024 6:54:03 AM</TRANSACTION_DATE>
    <CHILD_BATCHES>
        <CHILDBATCH>
            <BATCH_NUM>C101</BATCH_NUM>
            <QTY>1500</QTY>
        </CHILDBATCH>
        <CHILDBATCH>
            <BATCH_NUM>C102</BATCH_NUM>
            <QTY>2000</QTY>
        </CHILDBATCH>
    </CHILD_BATCHES>
</Root>';

-- INSERT INTO targetTable -- uncomment when you are ready
SELECT NEW_BATCH_NUM = p.value('(NEW_BATCH_NUM/text())[1]', 'VARCHAR(30)')
    , NEW_LOCATION = p.value('(NEW_LOCATION/text())[1]', 'VARCHAR(30)')
    , CHILD_BATCH_NUM  = c.value('(BATCH_NUM/text())[1]', 'VARCHAR(30)')
    , QTY  = c.value('(QTY/text())[1]', 'INT')
FROM @parameter.nodes('/Root') AS A(p)   -- parent
CROSS APPLY A.p.nodes('CHILD_BATCHES/CHILDBATCH') AS B(c); -- child

输出

NEW_BATCH_NUM NEW_LOCATION CHILD_BATCH_NUM 数量
A1234 美国11 C101 1500
A1234 美国11 C102 2000
© www.soinside.com 2019 - 2024. All rights reserved.