Postgres FOR LOOP的语法错误

时间:2010-05-15 08:33:17

标签: postgresql stored-procedures for-loop plpgsql

我在postgres函数中遇到问题:

CREATE OR REPLACE FUNCTION linkedRepoObjects(id bigint) 
        RETURNS int  AS $$ 
          DECLARE catNumber int DEFAULT 0;
          DECLARE cat RECORD;
        BEGIN
        WITH RECURSIVE children(categoryid,category_fk) AS (
         SELECT categoryid, category_fk
         FROM b2m.category_tab 
         WHERE categoryid = 1
           UNION ALL
         SELECT c1.categoryid,c1.category_fk
         FROM b2m.category_tab c1, children 
         WHERE children.categoryid = c1.category_fk
         )


    FOR cat IN SELECT * FROM children LOOP
      IF EXISTS (SELECT 1 FROM b2m.repoobject_tab WHERE category_fk = cat.categoryid)   THEN
            catNumber = catNumber +1
      END IF;
    END LOOP;

         RETURN catNumber;

         END;
    $$ LANGUAGE 'plpgsql';

我有错误:

FEHLER:  Syntax error near »FOR«
LINE 1: ...dren WHERE children.categoryid = c1.category_fk ) FOR  $2  I...

2 个答案:

答案 0 :(得分:3)

语法错误是因为期望WITH ...SELECT后面找到FOR

我没有在plpgsql中的查询中使用WITH子句,但我会尝试将FOR cat IN移到WITH之前,这是查询的一部分。

答案 1 :(得分:1)

试试这个:

CREATE OR REPLACE FUNCTION linkedRepoObjects(id bigint) RETURNS int AS 
$$ 
DECLARE catNumber int DEFAULT 0;
DECLARE cat RECORD;
BEGIN

    FOR cat IN    

        WITH RECURSIVE children(categoryid,category_fk) AS (
        SELECT categoryid, category_fk
        FROM b2m.category_tab 
        WHERE categoryid = 1
        UNION ALL
        SELECT c1.categoryid,c1.category_fk
        FROM b2m.category_tab c1, children 
        WHERE children.categoryid = c1.category_fk
        )
        SELECT * FROM children 

    LOOP

        IF EXISTS (SELECT 1 FROM b2m.repoobject_tab WHERE category_fk = cat.categoryid)   THEN
            catNumber = catNumber +1
        END IF;

    END LOOP;

    RETURN catNumber;

END;
$$ LANGUAGE 'plpgsql';

我注意到你的查询几乎不需要循环,只需这样做:

CREATE OR REPLACE FUNCTION linkedRepoObjects(id bigint) RETURNS int AS 
$$ 
BEGIN

    RETURN
    (  
    SELECT COUNT(*) FROM b2m.repoobject_tab WHERE category_fk IN 
        (
            WITH RECURSIVE children(categoryid,category_fk) AS 
            (
                SELECT categoryid, category_fk
                FROM b2m.category_tab 
                WHERE categoryid = 1
                UNION ALL
                SELECT c1.categoryid,c1.category_fk
                FROM b2m.category_tab c1, children 
                WHERE children.categoryid = c1.category_fk
            )
            SELECT categoryid FROM children 
        )
     );
END;
$$ LANGUAGE 'plpgsql';