【问题标题】:how to insert into type in postgresql type如何在 postgresql 类型中插入类型
【发布时间】:2020-10-22 13:56:39
【问题描述】:

我有一个表类型 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;

请帮忙

【问题讨论】:

  • 该类型在您的示例中似乎完全没用。

标签: types insert postgresql-9.4


【解决方案1】:

如果要创建“类型实例”,需要使用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 数组。自定义类型似乎没用。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-06-19
  • 2023-03-16
  • 2020-05-09
  • 1970-01-01
  • 2020-06-10
  • 2021-11-20
  • 2012-04-10
  • 2014-11-01
相关资源
最近更新 更多