我有以下功能......
CREATE OR REPLACE FUNCTION class_listing(var_sem integer, var_sy character) RETURNS SETOF RECORD AS
DECLARE
current_offering record;
BEGIN
SELECT subcode, offerno INTO current_offering FROM offering WHERE SY=var_sem AND SEM=var_sy;
END;
如何将current_offering
作为结果集返回?
答案 0 :(得分:2)
您可以使用SQL或PLpgSQL函数。使用匿名记录作为返回类型是不实际的(主要是在编写查询时不友好)。改为使用RETURNS TABLE或OUT参数。
CREATE OR REPLACE FUNCTION class_listing(var_sem integer, var_sy varchar)
RETURNS TABLE (subcode varchar, offerno int) AS $$
BEGIN
RETURN QUERY SELECT o.subcode, o.offerno
FROM offering
WHERE SY=var_sem AND SEM=var_sy;
END;
$$ LANGUAGE plpgsql;
或SQL语言
CREATE OR REPLACE FUNCTION class_listing(var_sem integer, var_sy varchar)
RETURNS TABLE (subcode varchar, offerno int) AS $$
SELECT o.subcode, o.offerno
FROM offering
WHERE SY=$1 AND SEM=$2;
$$ LANGUAGE sql;
注意 - 基于查询的函数作为优化器屏障工作(具有小的例外)。在复杂查询中使用它时要小心。
为了完整性 - 您的示例可以写成:
CREATE OR REPLACE FUNCTION class_listing(var_sem integer, var_sy varchar)
RETURNS SETOF RECORD AS $$
DECLARE current_offering record;
BEGIN
FOR current_offering IN
SELECT o.subcode, o.offerno
FROM offering
WHERE SY=var_sem AND SEM=var_sy;
LOOP
RETURN NEXT current_offering;
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql;
但现在不推荐使用此表单