从自定义类型数组插入到PostgreSql表中

时间:2018-09-18 11:55:06

标签: postgresql plpgsql

我这样创建一个自定义类型:

CREATE TYPE employee AS (employee_id INTEGER, name VARCHAR(200), age INTEGER);

然后我创建一个函数,该函数接收此类型的数组作为参数:

CREATE FUNCTION insert_office(v_office_id INTEGER, v_office_name VARCHAR(400), v_employees employee[])
RETURNS void
AS $BODY$

INSERT INTO office (office_id, office_name)
VALUES(v_office_id, v_office_name)

--here I need to insert the array of employees (v_employees) into the employees table

$BODY$
LANGUAGE SQL;

鉴于雇员表已设置为与雇员类型的属性匹配:

CREATE TABLE employee (employee_id INTEGER, name VARCHAR(200), age INTEGER)

我如何简单地将类型为employee的数组转移到employee表?尽管进行了几次尝试,但我无法正确使用语法。 (PostgreSQL 9.6)

1 个答案:

答案 0 :(得分:1)

您需要取消嵌套数组的元素:

insert into employees (employee_id, name, age)
select employee_id, name, age
from unnest(v_employees);