【发布时间】:2021-04-11 09:07:48
【问题描述】:
如何在 plpgsql 函数中访问 select 语句的结果以检查其内容?
我需要检查我使用的ilike 函数是否在我的people 表中返回任何匹配的演员。如果没有匹配项,我需要在“actor_details”表中返回“No matching name”,但如果有多个不同的值,我需要返回“Non-distinct actor name”之类的内容。
如果其中任何一个条件为真,我需要跳出函数并简单地在“actor_details”表中返回这些文本字符串。
在我的实际函数中,我需要在该语句之后附加几行文本,因此RETURNS table。
任何指针都会很棒。最后两行代码中定义的预期输出。
CREATE TABLE people (
id integer NOT NULL,
name text NOT NULL,
year_born integer,
year_died integer
);
insert into people (id, name, year_born, year_died) values
(20000007, 'Humphrey Bogart', 1899, 1957)
(20000008, 'Marlon Brando', 1924, 2004)
(20000009, 'Richard Burton', 1925, 1984)
(200000010, 'Richard Hunt', 1985, NULL)
CREATE OR REPLACE FUNCTION actor_details(_pattern text)
RETURNS table (actor_details text)
AS $$
BEGIN
select distinct concat(people.name, ' (', people.year_born, '-', people.year_died, ')')
into actor_details
from people
where people.name ilike('%' || _pattern || '%');
--- THIS IS WHERE I NEED HELP
IF (@@ROWCOUNT = 0) then
select 'No matching name' into actor_details;
ELSIF (@@ROWCOUNT > 1) then
select 'Non-distinct actor name';
END IF;
return;
END
$$
LANGUAGE plpgsql;
select * from actor_details('xxyyzz'); ---<<< Should return 'No matching name' in a column titled actor_details
select * from actor_details('Richarch'); ---<<< Should return 'Non-distinct actor name' in a column titled actor_details
【问题讨论】:
标签: sql postgresql