0

I have these Stored Procedure logic to be implemented:

CREATE OR REPLACE FUNCTION get_array(arraynumbers integer[])
RETURNS TABLE (name text) AS $$
DECLARE 
index integer := 0
BEGIN 
FOREACH index < arraynumbers
LOOP
SELECT e.name as empname FROM employee as e
WHERE e.id = arraynumbers[index]
LIMIT 1
name.push(empname)
ENDLOOP;
RETURN name;
END;
$$
LANGUAGE PLPGSQL;

The goal is to loop based on the length of the array parameter and every index of the parameter will be the condition for retrieving a record and push it to a variable and return the variable as table.

What is the correct way of writing it in PostgreSQL Stored Procedure?

3
  • 1
    What do you expect the non-existing push() method to do? Commented Aug 15, 2018 at 14:34
  • Hi @a_horse_with_no_name I wanted to append the result of the SELECT (which is a single record) to a variable in every loop. Commented Aug 15, 2018 at 14:35
  • But you declared the function as returns table so why are you appending everything to a single (non-existing) variable? Commented Aug 15, 2018 at 14:38

1 Answer 1

1

It's unclear to me what exactly the result should be, but as far as I can tell, you don't need a loop or a PL/pgSQL function:

CREATE OR REPLACE FUNCTION get_array(arraynumbers integer[])
  RETURNS TABLE (name text) 
AS 
$$
  SELECT e.name 
  FROM employee as e
  WHERE e.id = any(arraynumbers);
$$
LANGUAGE SQL;

This will return one row for each id in arraynumbers that exist in the employee table. As the function is declared as returns table there is no need to collect the values into a single variable (which you didn't declare to begin with)

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

1 Comment

I will try to implement this answer. If this answer solves the problem, I will indicate this as the correct answer.

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.