← 中文资源

简体中文版本

XMLTABLE 按 XPath 将 XML 节点展开为关系行

用 PostgreSQL 标准 XMLTABLE 配合 PASSING 与 XPath 把嵌套 XML 展开为强类型关系列,并用 FOR ORDINALITY 生成行号、DEFAULT 为缺失节点设默认值。

阅读英文原文

实现说明

实际执行的是 SELECT / INSERT / CREATE——invoice_batches 是涉及的对象。 invoice_batches 是文件自己造的会话级临时表——库里不会有残留,会话终结即被清理。 真正干活的子句:ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;补齐缺省列的 DEFAULT 值。

常见问题

这些语句涉及哪些表?

invoice_batches——直接调用该标识符本身,全程省略连接动作。

核心语句

INSERT INTO invoice_batches VALUES (
    1,
    XMLPARSE(DOCUMENT '<orders>
        <order id="101"><customer>Ada</customer><coupon>VIP10</coupon></order>
        <order id="102"><customer>Linus</customer></order>
    </orders>')
);
CREATE TEMP TABLE invoice_batches (
    batch_id integer PRIMARY KEY,
    payload  xml NOT NULL
);

代码示例

CREATE TEMP TABLE invoice_batches (
    batch_id integer PRIMARY KEY,
    payload  xml NOT NULL
);

INSERT INTO invoice_batches VALUES (
    1,
    XMLPARSE(DOCUMENT '<orders>
        <order id="101"><customer>Ada</customer><coupon>VIP10</coupon></order>
        <order id="102"><customer>Linus</customer></order>
    </orders>')
);

SELECT
    b.batch_id,
    x.line_no,
    x.order_id,
    x.customer,
    x.coupon
FROM invoice_batches b,
XMLTABLE(
    '/orders/order'
    PASSING b.payload
    COLUMNS
        line_no  FOR ORDINALITY,
        order_id integer PATH '@id',
        customer text    PATH 'customer' NOT NULL,
        coupon   text    PATH 'coupon' DEFAULT 'NONE'
) AS x
ORDER BY b.batch_id, x.line_no;