← 中文资源

简体中文版本

ALTER COLUMN TYPE 与 USING 迁移

改列类型时 USING 表达式负责旧值到新域的换算:integer 除以 100 得 numeric(10,2),text 转 integer 也要显式 ::integer,存量行安全迁移。

阅读英文原文

实现说明

一个文件里不止一条语句:SELECT / INSERT / UPDATE / CREATE / ALTER,invoices 都在涉及之列。 具体组合了这些手段:ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。

常见问题

这个文件引用了哪些表?

invoices——直接引用,无需连接。

核心语句

CREATE TABLE invoices (
    id          bigserial PRIMARY KEY,
    total_cents integer NOT NULL
);
SELECT id, total_cents, quantity FROM invoices ORDER BY id;
INSERT INTO invoices (total_cents) VALUES (1250), (99);

代码示例

-- 改列类型:USING 表达式负责旧值到新域的换算,存量行安全迁移
CREATE TABLE invoices (
    id          bigserial PRIMARY KEY,
    total_cents integer NOT NULL
);
INSERT INTO invoices (total_cents) VALUES (1250), (99);

-- integer -> numeric(10,2):USING 把分单位的旧值换算成元
ALTER TABLE invoices
    ALTER COLUMN total_cents TYPE numeric(10,2)
    USING (total_cents::numeric / 100);

SELECT id, total_cents FROM invoices ORDER BY id;

-- text -> integer 反向迁移同样需要显式 USING 转换
ALTER TABLE invoices ADD COLUMN quantity text;
UPDATE invoices SET quantity = '2';
ALTER TABLE invoices
    ALTER COLUMN quantity TYPE integer
    USING quantity::integer;

SELECT id, total_cents, quantity FROM invoices ORDER BY id;