← 中文资源

简体中文版本

生成列的 DEFAULT 更新与 DROP EXPRESSION 解除

演示在 UPDATE 中通过 SET subtotal_cents = DEFAULT 触发 STORED 生成列重算,并用 ALTER TABLE DROP EXPRESSION 保留现有数据把生成列转为普通可写列。

阅读英文原文

实现说明

一个文件里不止一条语句:INSERT / UPDATE / CREATE / ALTER,invoice_items 都在涉及之列。 invoice_items 是由本文件里的语句当场建出来的会话级临时表——只活在当前会话,会话结束就自动清掉。 把语句拆开看,工作部件是:WHERE 决定这条语句会作用到哪些行;RETURNING 把受影响的行交回调用方;CHECK 约束在写入时就把越界值拒之门外;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;补齐缺省列的 DEFAULT 值;自动算列值的 GENERATED ALWAYS/GENERATED BY 子句。

常见问题

说出这个文件涉及的表。

invoice_items——直接调用标识名,不走外部连接步骤。

核心语句

UPDATE invoice_items
SET qty = 4, subtotal_cents = DEFAULT
WHERE item_id = 1
RETURNING item_id, qty, subtotal_cents;
UPDATE invoice_items
SET subtotal_cents = 5500
WHERE item_id = 1
RETURNING item_id, unit_cents, qty, subtotal_cents;
CREATE TEMP TABLE invoice_items (
    item_id        integer PRIMARY KEY,
    unit_cents     integer NOT NULL,
    qty            integer NOT NULL CHECK (qty > 0),
    subtotal_cents integer GENERATED ALWAYS AS (unit_cents * qty) STORED
);

代码示例

CREATE TEMP TABLE invoice_items (
    item_id        integer PRIMARY KEY,
    unit_cents     integer NOT NULL,
    qty            integer NOT NULL CHECK (qty > 0),
    subtotal_cents integer GENERATED ALWAYS AS (unit_cents * qty) STORED
);

INSERT INTO invoice_items (item_id, unit_cents, qty) VALUES
    (1, 1500, 2),
    (2, 800,  3);

-- Changing base columns recomputes subtotal_cents; only DEFAULT is allowed explicitly
UPDATE invoice_items
SET qty = 4, subtotal_cents = DEFAULT
WHERE item_id = 1
RETURNING item_id, qty, subtotal_cents;

-- Convert the generated column into a regular writable column, preserving values
ALTER TABLE invoice_items
    ALTER COLUMN subtotal_cents DROP EXPRESSION;

UPDATE invoice_items
SET subtotal_cents = 5500
WHERE item_id = 1
RETURNING item_id, unit_cents, qty, subtotal_cents;