postgreSQL Fibonacci Sequence - Query has no destination for result data

泄露秘密 提交于 2021-02-08 06:23:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!