我正在学习postgresql,并想知道我是否可以在存储过程中添加长选项 像这样一个人应该从两个连接的表中返回select:
CREATE OR REPLACE FUNCTION api.book_list()
RETURNS TABLE (
id BIGINT,
published DATE,
category VARCHAR,
author VARCHAR,
name VARCHAR
) AS $$
BEGIN
SELECT
b.id,
b.published,
c.name AS category,
b.author,
b.name
FROM
schemas.book AS b
JOIN
schemas.category AS c
ON
c.id = b.category_id;
END;
$$
LANGUAGE plpgsql;
给出错误:
select * from api.book_list();
ERROR: query has no destination for result data
HINT: If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT: PL/pgSQL function "book_list" line 3 at SQL statement
答案 0 :(得分:2)
对于像这样的简单查询,我会使用VIEW
或SQL function:
CREATE OR REPLACE FUNCTION api.book_list()
RETURNS TABLE (
id bigint,
published date,
category varchar,
author varchar,
name varchar) AS
$func$
SELECT b.id
,b.published
,c.name -- AS category -- alias irrelevant and conflicts with OUT param
,b.author
,b.name
FROM schemas.book b
JOIN schemas.category c ON c.id = b.category_id
$func$
LANGUAGE sql;
然后,您不需要BEGIN
,END
或plpgsql
,就像使用{{1}}一样。
答案 1 :(得分:1)
尝试:
BEGIN
return query
SELECT
b.id,
b.published,
c.name AS category,
b.author,
b.name
FROM
schemas.book AS b
JOIN
schemas.category AS c
ON
c.id = b.category_id;
END;