【问题标题】:How can I pass table data into a function using a PostgresSQL composite type?如何使用 PostgresQL 复合类型将表数据传递到函数中?
【发布时间】:2019-09-01 00:08:57
【问题描述】:

我想使用composite type 将数据传递到函数中。但是,我看不到如何调用该函数。考虑以下代码:

drop table if exists ids cascade;
create table ids
(
    id bigint primary key
);

drop table if exists data;
create table data
(
    id   bigint generated always as identity primary key references ids(id) deferrable initially deferred,
    name text
);

drop type if exists raw_type cascade;
create type raw_type as (name text);
create table raw2 of raw_type;

insert into raw2(name)
values ('test1'),
       ('test2'),
       ('test3'),
       ('test4'),
       ('test5'),
       ('test6'),
       ('test7')
;

create or replace function special_insert(data_to_insert raw_type) returns void as
    $func$
    begin
    with x as (insert into data(name) select name from data_to_insert returning id)
    insert into ids(id)
    select id from x;
    end;
$func$ language plpgsql;

运行这个:

begin transaction ;
select special_insert(raw2);
commit ;

我收到以下错误:

ERROR: column "raw2" does not exist

运行这个:

begin transaction ;
select special_insert(name::raw_type) from raw2;
commit ;

我明白了

[2019-04-10 15:41:18] [22P02] ERROR: malformed record literal: "test1"
[2019-04-10 15:41:18] Detail: Missing left parenthesis.

我做错了什么?

【问题讨论】:

    标签: postgresql composite-types


    【解决方案1】:

    第二个函数调用是正确的,但是你的函数定义中有一个错误。

    您错误地将data_to_insert 视为一个表,但它是单个值。使用以下表示法从复合类型中获取单个字段:

    INSERT INTO data (name)
    VALUES (data_to_insert.name)
    RETURNING id
    

    【讨论】:

    • 啊哈!我在文档中看到了该语法,但没有将其与我的实现联系起来。但是,有没有办法传入整个值表?这就是我真正想要做的。
    • 使用data_to_insert.*
    • 谢谢,那是每行调用一次函数还是每条语句调用一次?
    • 显然每行一次:该函数接受一个raw_type 作为参数并返回一个void,即什么都没有。
    猜你喜欢
    • 2015-12-13
    • 2023-03-03
    • 2012-05-10
    • 2014-07-16
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多