如何在pl pgsql中返回选择查询

时间:2019-03-29 18:28:42

标签: postgresql

在运行Select查询时,返回Pl Pgsql中的所有列 用函数编写 在传递参数错误时显示。

CREATE OR REPLACE FUNCTION myfunc(ENROLL VARCHAR(50)) RETURNS  SETOF RECORD AS $$
DECLARE CALTYPE VARCHAR(50);
BEGIN
SELECT COMPLETED INTO 
CALTYPE FROM TEMPDATA WHERE
ROLL=ENROLL;
    IF CALTYPE='FALSE' THEN
        RETURN QUERY
        SELECT * FROM SEM8
        WHERE ROLL=ENROLL;
    ELSE
        RETURN QUERY
        SELECT * FROM TEMPDATA
        WHERE ROLL=ENROLL;
    END IF;
END;
$$ LANGUAGE plpgsql;

SELECT * FROM myfunc('123');

1 个答案:

答案 0 :(得分:1)

返回SETOF RECORD的函数需要列定义。您可以在运行时定义它,如下所示:

SELECT * FROM myfunc('123') mf(columnA TEXT, columnB INTEGER);

或者您可以将函数的返回类型更改为TABLE并在其中定义它,如下所示:

CREATE OR REPLACE FUNCTION myfunc(ENROLL VARCHAR(50)) 
RETURNS  TABLE (
    columnA TEXT,
    columnB INTEGER
) AS $$
DECLARE CALTYPE VARCHAR(50);
BEGIN
SELECT COMPLETED INTO 
CALTYPE FROM TEMPDATA WHERE
ROLL=ENROLL;
    IF CALTYPE='FALSE' THEN
        RETURN QUERY
        SELECT * FROM SEM8
        WHERE ROLL=ENROLL;
    ELSE
        RETURN QUERY
        SELECT * FROM TEMPDATA
        WHERE ROLL=ENROLL;
    END IF;
END;
$$ LANGUAGE plpgsql;