我正尝试在PL/pgSQL IF语句中使用以下代码运行SELECT查询:

DO
$do$
DECLARE
    query_type   real;
    arr real[] := array[1];
BEGIN
    IF query_type = 1 THEN
        RETURN QUERY
        SELECT "Westminster".*
        FROM "Westminster"
        WHERE ("Westminster".intersects = false AND "Westminster".area <= 100);
    ELSE IF query_type = 0 THEN
        RETURN QUERY
        SELECT "Westminster".*
        FROM "Westminster";
    END IF;
END
$do$

但是我得到了以下错误,ERROR: cannot use RETURN QUERY in a non-SETOF function
有人知道我怎样才能让上面的代码工作吗?谢谢您。
更新:这对我有效:
CREATE OR REPLACE FUNCTION my_function(query_type integer)
RETURNS SETOF "Westminster" LANGUAGE plpgsql as $$
BEGIN
    IF query_type = 1 THEN
        RETURN QUERY
        SELECT "Westminster".*
        FROM "Westminster"
        WHERE ("Westminster".intersects = false AND "Westminster".area <= 100);
    ELSIF query_type = 0 THEN
        RETURN QUERY
        SELECT "Westminster".*
        FROM "Westminster";
    END IF;
END;
$$;

然后我像这样调用函数:
SELECT * FROM my_function(1);

最佳答案

the documentation:
代码块被视为没有参数的函数体,返回void。
只能在返回RETURN QUERYSETOF <type>的函数中使用TABLE(...)。使用表"Westminster"作为结果类型,例如:

CREATE OR REPLACE FUNCTION my_function(query_type int)
RETURNS SETOF "Westminster" LANGUAGE plpgsql as $$
BEGIN
    IF query_type = 1 THEN
        RETURN QUERY
        SELECT "Westminster".*
        FROM "Westminster"
        WHERE ("Westminster".intersects = false AND "Westminster".area <= 100);
    ELSIF query_type = 0 THEN
        RETURN QUERY
        SELECT "Westminster".*
        FROM "Westminster";
    END IF;
END;
$$;

-- exemplary use:

SELECT * FROM my_function(1);

注意正确使用ELSIF

关于postgresql - 如何在PL/pgSQL IF语句中运行SELECT查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51040640/

10-13 09:31