【问题标题】:In Postgres sql Insert to table using user defined datatype在 Postgresql 中使用用户定义的数据类型插入到表中
【发布时间】:2022-11-17 16:27:14
【问题描述】:

问题是,在 PostgreSQL 中如何使用输入参数是用户定义数据类型的过程或函数插入到表中?

在下面的代码中,当我们运行错误“:错误:关系”时抛出。如何使用直接用户定义的数据类型进行插入。

旁注:在 stackoverflow 中有很多使用 UDT 直接插入的示例,但这里的问题是特定于从存储过程或函数插入的。

CREATE SCHEMA tooldb;
CREATE TYPE  tooldb.point AS
(
  firstpoint  int,
  lastpoint int
);

create table if not exists tooldb.points(
    firstpoint int,
    lastpoint int
);

CREATE OR REPLACE procedure tooldb.point_insert(
    in_point tooldb.point
)

LANGUAGE plpgsql AS  $$
BEGIN
    insert into tooldb.points (firstpoint, lastpoint)
    select firstpoint , lastpoint from in_point;
END  $$;


call tooldb.point_insert((3,5));

过程调用失败

psql:commands.sql:24: ERROR:  relation "in_point" does not exist
LINE 2:     select firstpoint , lastpoint from in_point

【问题讨论】:

  • insert into tooldb.points (firstpoint, lastpoint) values (in_point.firstpoint, in_point.lastpoint);
  • 谢谢你。这样可行。我们如何插入多行?我的意思是,我们应该使用数组参数吗?
  • 是的。然后该过程应具有in_point tooldb.point[]参数。我将在下面更新我的答案。

标签: postgresql sql-insert user-defined-types


【解决方案1】:

不需要 PL/pgSQL,普通 SQL 就足够了。

CREATE OR REPLACE procedure tooldb.point_insert(in_point tooldb.point)
language sql as
$$
 insert into tooldb.points (firstpoint, lastpoint)
 values (in_point.firstpoint, in_point.lastpoint);
$$;

要插入多行,您可以提供一个 tooldb.point 数组作为过程参数:

CREATE OR REPLACE procedure tooldb.point_insert(in_point tooldb.point[])
language sql as
$$
 insert into tooldb.points (firstpoint, lastpoint)
 select el.firstpoint, el.lastpoint from unnest(in_point) as el;
$$;

【讨论】:

    猜你喜欢
    • 2018-12-15
    • 2016-03-05
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    相关资源
    最近更新 更多