现在我有以下程序:
CREATE OR REPLACE FUNCTION find_city_by_name(match varchar) RETURNS TABLE(city_name varchar) LANGUAGE plpgsql as $$
BEGIN
RETURN QUERY WITH r AS (
SELECT short_name FROM geo_cities WHERE short_name ILIKE CONCAT(match, '%')
)
SELECT r.short_name FROM r;
END;
$$
我想要返回所有字段(*
)(不仅仅是short_name
)。我需要在手术中改变什么?
答案 0 :(得分:3)
以下是我在相邻答案的评论中提到的简化版(无WITH
和language sql
)版本:
create or replace function find_city_by_name(text)
returns table(city_name varchar, long_name varchar)
as $$
select * from geo_cities where short_name ilike $1 || '%';
$$ language sql;
此外,您可能会发现使用geo_cities
引用定义函数签名的SETOF geo_cities
表本身更方便:
create or replace function find_city_by_name(text)
returns setof geo_cities
as $$
select * from geo_cities where short_name ilike $1 || '%';
$$ language sql;
- 这将允许您更改geo_cities
表的结构,而无需更改函数的定义。
答案 1 :(得分:1)
如果你想要一个真正的行,你必须显式声明return clausule中的所有字段:
create table geo_cities (
short_name varchar,
long_name varchar
);
insert into geo_cities values ('BERLIN', 'BERLIN'), ('BERLIN 2','BERLIN TWO');
CREATE OR REPLACE FUNCTION find_city_by_name(match varchar)
RETURNS TABLE(city_name varchar, long_name varchar)
LANGUAGE plpgsql
AS
$$
BEGIN
RETURN QUERY WITH r AS (
SELECT * FROM geo_cities WHERE short_name ILIKE CONCAT(match, '%')
)
SELECT * FROM r;
END;
$$;
select * from find_city_by_name('BERLIN');
的示例