pgadmin 4版本2中无法使用SET OF记录或返回表(col1,[col2])返回类型?

问题描述 投票:0回答:2

基本上我想基于分隔符拆分字符串,例如: - “this,is,foo”应该返回这是foo,即;没有逗号分成单独的记录。我正在尝试使用pgadmin 4版本2。

这是我在功能对话框中想要的示例代码: -

create or replace function STRING_SPLIT(str text,delimiter character)
return SET OF record;
as 
begin
return QUERY SELECT trim(a)
FROM unnest(string_to_array('john,smith,jones', ',')) AS a; //str, delim
end

我基本上试图将扩展的行数组插入到记录集中。我尝试创建表并在return语句中返回它,但无法在pgadmin的函数对话框中指定列名,我也找不到同一对话框中的“set of record”返回类型?

有人可以帮忙吗?

sql postgresql plpgsql stored-functions pgadmin-4
2个回答
0
投票

在几乎所有情况下,使用returns table()是更好的解决方案。

create or replace function STRING_SPLIT(str text,delimiter character)
   return table(word text) --<< no ; here!!
as 
$$ --<< you need quotes around the body
  SELECT trim(a) as word
  FROM unnest(string_to_array(text, delimiter)) AS t(a);
$$
language sql; --<< no PL/pgSQL required, SQL is enough

如果您确实想使用setof record,那么在使用该函数时总是必须指定列名:

create or replace function STRING_SPLIT(str text,delimiter character)
   return setof record
as 
$$ --<< you need quotes around the body
  SELECT trim(a) as word
  FROM unnest(string_to_array(text, delimiter)) AS t(a);
$$
language sql; --<< no PL/pgSQL required, SQL is enough

然后:

select *
from string_split('foo,bar',',') as t(word);

但是,Postgres已经有了一个内置功能:

select *
from regexp_split_to_table('foo,bar',',') as t(word);

0
投票

虽然这篇文章较旧,但需要在这里发布答案。所以它会帮助像我这样的人。正如我一直在寻找同样的答案。在pgAdmin4中,'setof'在返回类型中不存在。使用create function window在pgAdmin中创建函数时,需要选择record作为返回类型。 Then click on the options and set "Returns a set?" to "Yes". like this

然后它将自动将setof记录作为返回类型,并将在sql viwer中的代码中显示,但不会在选择的返回类型中显示。

Then it will automatically take setof record as a return type and will show in code in sql viwer, but not in return type selected.

© www.soinside.com 2019 - 2024. All rights reserved.