如何在postgresql类型中插入类型

how to insert into type in postgresql type

我有一个 table 类型的 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

returned id 列的类型也不匹配 - 它必须是 bigint 才能匹配类型中的列。

您的最终 select 与函数结果的定义不匹配。 unnest(list) 将 return 类型为 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 数组。自定义类型似乎没用。