如何在PL / pgSQL IF语句中运行SELECT查询

时间:2018-06-26 10:28:33

标签: postgresql if-statement select plpgsql

我正在尝试使用以下代码在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);

2 个答案:

答案 0 :(得分:3)

来自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

答案 1 :(得分:1)

我不认为anonymous code blocks支持它。尝试创建一个函数并将其结果集定义为table,例如:

CREATE OR REPLACE FUNCTION myfunc() RETURNS TABLE (val INT) AS $$
BEGIN
  RETURN QUERY SELECT 1;
END;
$$ LANGUAGE plpgsql;

要调用函数,可以使用:

SELECT * FROM myfunc();

注意:请记住,在函数标头上声明的表需要具有RETURN QUERY语句中返回的相同字段。