微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在PostgreSQL类型中插入类型

如何解决如何在PostgreSQL类型中插入类型

我有一个表类型为newIntList

CREATE TYPE newIntList AS
(
    id bigint
);

想要在类型变量中插入一个整数值。

尝试下面的代码,不起作用。...

  CREATE OR REPLACE FUNCTION insertintoType(n1 integer) 
    RETURNS table(id integer) AS $$
    declare
    list newIntList[];
    BEGIN
    
    insert into list
    select n1;    //looking for a code for inserting into Type "**newIntList**"
    
    
    return query 
    select unnest(list );
    END; $$
    LANGUAGE PLPGsql;

请帮助

解决方法

如果要创建“类型实例”,则需要使用row constructor

要将元素放入数组中,只需assign,就不必使用insert

返回的id列的类型也不匹配-必须为bigint才能匹配类型中的列。

您的最终选择与函数结果的定义不匹配。 unnest(list)将返回类型为newintlist的单列,而不是整数(或bigint)。您需要使用select * from unnest(...)来实现。

因此函数应如下所示:

CREATE OR REPLACE FUNCTION insertintoType(n1 integer) 
  RETURNS table(id bigint) --<< match the data type in newintlist
AS $$
declare
  list newintlist[];
BEGIN
  list[0] := row(n1); --<< create a new "instance" of the type and assign it to the first element
  
  return query 
    select * 
    from unnest(list) as l(id);
END; $$
LANGUAGE PLPGSQL;

然后像这样使用它:

select *
from insertintotype(1);

但是我看不到为什么您不仅仅在函数内部使用整数或bigint数组。自定义类型似乎没用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。