问题
So I wrote a Fibonacci sequence function like this:
CREATE OR REPLACE FUNCTION fibonacci (lastN INTEGER)
RETURNS int AS $$
BEGIN
WITH RECURSIVE t(a, b) AS (
VALUES(0,1)
UNION ALL
SELECT GREATEST(a, b), a + b AS a from t
WHERE b < $1
)
SELECT a FROM t;
END;
$$ LANGUAGE plpgsql;
But when I called:
SELECT * FROM fibonacci(20);
the console shows:
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 fibonacci(integer) line 5 at SQL statement
I think the Return statement should return the query result but it isn't. I'm completely a new guy on writing SQL functions like this.
回答1:
You are close. Basically your SELECT
is leading to nowhere and your function header says it is supposed to return a INT
value. Since it is a pure SQL
query using CTE
, there is no need to use PLPGSQL
, so I also changed the language type to SQL
CREATE OR REPLACE FUNCTION fibonacci (lastN INTEGER)
RETURNS SETOF INTEGER LANGUAGE SQL AS $$
WITH RECURSIVE t(a, b) AS (
VALUES(0,1)
UNION ALL
SELECT GREATEST(a, b), a + b AS a from t
WHERE b < $1
)
SELECT a FROM t;
$$;
SELECT fibonacci(20);
EDIT: as requested, the same function using the language PLPGSQL
CREATE OR REPLACE FUNCTION fibonacci (lastN INTEGER)
RETURNS SETOF INT LANGUAGE PLPGSQL AS $$
BEGIN
RETURN QUERY WITH RECURSIVE t(a, b) AS (
VALUES(0,1)
UNION ALL
SELECT GREATEST(a, b), a + b AS a from t
WHERE b < $1
)
SELECT a FROM t;
END $$;
SELECT fibonacci(20);
来源:https://stackoverflow.com/questions/49307655/postgresql-fibonacci-sequence-query-has-no-destination-for-result-data