4

In this postgressql function i created a array by spliting a string. Now i want loop on this array and do some processing on it.

Function:

CREATE OR REPLACE FUNCTION getAllFoo() RETURNS character varying as
$BODY$
DECLARE
   arr_split_data text[];
   counter character varying;
begin

    counter := ''; -- Init value

    -- split data. Add in array
    select into arr_split_data regexp_split_to_array('a,b,c,d,e,f',',');

    FOR r IN arr_split_data -- error
    LOOP
         counter := arr_split_data[r] || '_' || counter; -- do some processing
    END LOOP;

  return counter;
END
$BODY$
LANGUAGE 'plpgsql';

But I am getting this error

error

when I execute this function. Is my syntax for loop is wrong?

2 Answers 2

10

The syntax is

FOREACH r IN ARRAY arr_split_data
LOOP
  counter := r || '_' || counter;
  -- do some processing
END LOOP;

You'll need to declare r too:

DECLARE
    arr_split_data TEXT [];
    r              CHARACTER VARYING;
    counter        CHARACTER VARYING;
BEGIN

See section 41.6.5 of the manual: Looping Through Arrays

Sign up to request clarification or add additional context in comments.

2 Comments

not working. Error - loop variable of FOREACH must be a known variable or list of variables
@Deepakgupta: then declare the variable r
8
    CREATE OR REPLACE FUNCTION getAllFoo() RETURNS character varying as
    $BODY$
    DECLARE
        r               character varying;    
        arr_split_data  text[];
        counter         character varying;
    begin
        counter := ''; -- Init value

        -- split data. Add in array
        select into arr_split_data regexp_split_to_array('a,b,c,d,e,f',',');

        FOREACH r IN array arr_split_data LOOP
            counter := counter || '_' || r; -- do some processing
        END LOOP;
        return counter;

    END
    $BODY$
    LANGUAGE 'plpgsql';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.