views:

208

answers:

2

Hi all,

Ich have a problem in postgres function:


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



  

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

I'm a newbee in Postgres. Please help. Thanx in advance

A: 

The syntax error is because it is expecting the WITH ... to be followed by SELECT where it found FOR.

I haven't used WITH clauses in queries in plpgsql, but I'd try moving FOR cat IN to before the WITH, which is part of the query.

Stephen Denne
Thanx a lot.it helped.
easyrider
A: 

Try this:

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

I noticed your query hardly needs looping, just do this:

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';
Michael Buen
by which time, it can be made into a language 'sql' function...
araqnid
indeed, i just got accustomed with plpgsql :-)
Michael Buen