有条件地覆盖单个插入中的默认 PK 序列
Conditionally Override Default PK Sequence in Single Insert
假设我将 table customer2 定义为:
CREATE TABLE customer2(
customer_id bigint NOT NULL DEFAULT nextval(('customer.customer_identity'::text)::regclass),
customer_name character varying
CONSTRAINT customer2_pkey PRIMARY KEY (customer_id)
)
我有另一个名为 customer1 的 table,具有相同的 table 定义。在插入 customer2 之前,我想检查 customer1 以查看 customer_id 是否存在相同的 customer_name,如果存在则使用它。我的插入语句类似于:
INSERT INTO customer2(
customer_id,
customer_name)
SELECT customer_id, --null if not found in customer1 table
nc.customer_name
FROM new_customers nc
LEFT OUTER JOIN customer1 c1 on c1.customer_name = nc.customer_name
当 运行 此插入时,我收到错误 "null value in column "customer_id“违反非空约束”。当我没有要插入的 customer_id 时,有没有办法使用默认序列?显然,我可以编写两个不同的插入语句,但很遗憾,这是重要且看似不必要的代码重复,这让我的编程天性感到厌烦。
你不能只使用 coalesce
和 nextval
来仅在序列为 null 时使用它。
INSERT INTO customer2(
coalesce(customer_id, nextval('customer.customer_identity')),
customer_name)
SELECT customer_id, --null if not found in customer1 table
nc.customer_name
FROM new_customers nc
LEFT OUTER JOIN customer1 c1 on c1.customer_name = nc.customer_name
假设我将 table customer2 定义为:
CREATE TABLE customer2(
customer_id bigint NOT NULL DEFAULT nextval(('customer.customer_identity'::text)::regclass),
customer_name character varying
CONSTRAINT customer2_pkey PRIMARY KEY (customer_id)
)
我有另一个名为 customer1 的 table,具有相同的 table 定义。在插入 customer2 之前,我想检查 customer1 以查看 customer_id 是否存在相同的 customer_name,如果存在则使用它。我的插入语句类似于:
INSERT INTO customer2(
customer_id,
customer_name)
SELECT customer_id, --null if not found in customer1 table
nc.customer_name
FROM new_customers nc
LEFT OUTER JOIN customer1 c1 on c1.customer_name = nc.customer_name
当 运行 此插入时,我收到错误 "null value in column "customer_id“违反非空约束”。当我没有要插入的 customer_id 时,有没有办法使用默认序列?显然,我可以编写两个不同的插入语句,但很遗憾,这是重要且看似不必要的代码重复,这让我的编程天性感到厌烦。
你不能只使用 coalesce
和 nextval
来仅在序列为 null 时使用它。
INSERT INTO customer2(
coalesce(customer_id, nextval('customer.customer_identity')),
customer_name)
SELECT customer_id, --null if not found in customer1 table
nc.customer_name
FROM new_customers nc
LEFT OUTER JOIN customer1 c1 on c1.customer_name = nc.customer_name