简体   繁体   English

创建连接并返回多于一行的 Postgres function

[英]Create Postgres function that concats and returns more than one row

I have played around with this for a few hours and it seems to be going over my head.我已经玩了几个小时了,这似乎超出了我的想象。

I am a novice at SQL and am attempting to create a simple function to concat first_name and last_name rows into a staff_fname table.我是 SQL 的新手,我正在尝试创建一个简单的 function 以将 first_name 和 last_name 行连接到 staff_fname 表中。

Using this code returns the results just fine and populates staff_fname, concatenating each first name and last name entry from the source table:使用此代码可以很好地返回结果并填充 staff_fname,连接源表中的每个名字和姓氏条目:

SELECT
CONCAT (first_name, ' ', last_name) INTO staff_fname
FROM staff;

However, when I try to insert this into a function, it does not work properly:但是,当我尝试将其插入 function 时,它无法正常工作:

CREATE FUNCTION connames()
RETURNS varchar(90)
LANGUAGE plpgsql
AS $$
DECLARE staff_fname varchar(90);
BEGIN
    SELECT
    CONCAT (first_name, ‘ ’, last_name) INTO staff_fname
    FROM staff;

    RETURN staff_fname;
END;
$$;

When I try to call the function connames(), it only concats and returns one row (the first row).当我尝试调用 function connames() 时,它只连接并返回一行(第一行)。 I have tried playing around with LOOP, RETURNS SETOF, and RETURN QUERY to no avail.我尝试过使用 LOOP、RETURNS SETOF 和 RETURN QUERY,但无济于事。 I am sure it is simple but I can't figure it out.我确信这很简单,但我无法弄清楚。

It would be like这就像

create or replace function connames()
returns setof text as 
$$
begin
 return query execute E'select CONCAT (first_name,\' \', last_name) FROM staff';
end;
$$ language plpgsql;

and execution和执行

select connames() into staff_fname;

Should be simple using language SQL使用语言 SQL 应该很简单

create or replace function connames() returns setof text as 
$$
  select concat(first_name, ' ', last_name) from staff;
$$
language sql stable;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM