2010-05-15 80 views
-1

我在Postgres的功能相關的問題:語法錯誤在Postgres FOR循環

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... 

回答

3

的語法錯誤是因爲它是期待WITH ...要遵循通過SELECT它發現了FOR

我還沒有在plpgsql的查詢中使用WITH子句,但是我會嘗試將​​移動到WITH之前,這是查詢的一部分。

+0

親切廣告樣本:( – 2011-06-01 10:11:32

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'; 
+0

到那個時候,就可以做成一個語言「 sql'函數... – araqnid 2010-05-15 12:01:39

+0

的確,我只習慣了plpgsql :-) – 2010-05-15 13:37:00