0

我正在学习 postgresql 并且想知道我是否可以将长选择放入存储过程中,例如应该从两个连接表中返回选择的存储过程:

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
4

2 回答 2

2

对于像这样的简单查询,我会使用一个VIEW或一个SQL 函数

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;

然后你不需要RETURN QUERYBEGIN或者END像你一样使用plpgsql

于 2012-12-31T19:27:28.873 回答
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;
于 2012-12-31T18:59:35.423 回答