首页 > 解决方案 > Postgresql 从复合类型数组和一个附加列中多插入

问题描述

我有的:

CREATE TYPE Item AS (
    a bigint,
    b bigint
);

CREATE TABLE items (
    id bigint NOT NULL,
    a bigint NOT NULL,
    b bigint NOT NULL
);

CREATE OR REPLACE FUNCTION items_insert(
        _id bigint,
        _items Item[]
) RETURNS void AS
...

如何通过一个多插入查询将多行插入到 _items 中具有相同 _id 的表项?

我正在使用 Postgresql-9.2

标签: postgresqlsql-insertpostgresql-9.2

解决方案


我认为您的意思是“插入多”而不是列。

假设这是正确的,我认为您正在寻找这样的功能:

create or replace function items_insert(_id bigint, _items item[]) 
  returns void 
as
$$
  insert into items (id, a, b)
  select _id, it.*
  from unnest(_items) as it(a,b);
$$
language sql;

在线示例


推荐阅读