if条件中基于查询结果的循环语法

时间:2016-06-15 06:55:19

标签: postgresql function loops

我是PGSQL的新手并尝试在数据库函数中启动循环,该循环基于查询结果进行迭代,如下所示。我使用的是8.2版本。

CREATE OR REPLACE FUNCTION demo(text)
RETURNS SETOF activityhistoryview
    LANGUAGE plpgsql STABLE
    AS $_$
DECLARE
tilldate ALIAS for $1;
actrec revpro_500.activity%ROWTYPE;
BEGIN
    IF tilldate != '' THEN
        FOR actrec IN
            SELECT activity.* from revpro_500.activity WHERE activity.householdid = 950
        LOOP
    ELSE
        FOR actrec IN
            SELECT activity.* from revpro_500.activity WHERE activity.householdid = 500
        LOOP    
    END IF;

        BEGIN
        /* rest code goes here */
        END
    END LOOP;
    RETURN;
END;$_$;

执行上述功能后,我收到以下错误。

错误:“ELSE”或附近的语法错误

我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

你不能像这样嵌套循环查询。相反,首先评估您要对tilldate执行的操作,然后进行单循环查询:

CREATE OR REPLACE FUNCTION demo(tilldate text) RETURNS SETOF activityhistoryview
    LANGUAGE plpgsql STABLE AS $_$
DECLARE
    actrec revpro_500.activity%ROWTYPE;
    hhid integer;
BEGIN
    IF tilldate != '' THEN
        hhid = 950;
    ELSE
        hhid = 500;
    END IF;

    FOR actrec IN
        SELECT * from revpro_500.activity WHERE householdid = hhid
    LOOP
        BEGIN -- Do you really need a transaction block? If not, remove BEGIN/END
        -- rest code goes here
        END
    END LOOP;
    RETURN;
END;$_$;

答案 1 :(得分:0)

与大多数语言一样,您的控制结构不能重叠,因此在ELSE打开LOOP之前的行,但不要在ELSE之前关闭它},因此ELSE没有与其配对的IF

您可以将IF / ELSE块放在循环内部或其外部,但不能重叠。

示例:

-- Good
LOOP
    -- some computations
    IF tilldate != '' THEN
        EXIT;  -- exit loop
    ELSE
        -- some computations
    END IF;
END LOOP;

-- Good
IF tilldate != '' THEN
    LOOP
        -- some computations
    END LOOP;
ELSE
    LOOP
        -- some computations
    END LOOP;
END IF;    

-- Bad
IF
    LOOP
        -- some computations
ELSE
    -- some computations
END IF;
END LOOP;