2

I've only recently begun dabbling with PostgreSQL and I've been building functions to handle the necessary tasks.

There is a table called queue, into which new tasks are added with status of "New". The function below should update these new tasks and return their queueid column values, which are bigint serials. Since there may be none, one or more tasks, I need to be able to return none, one or more values too.

Returning these values have me up against a wall. I've been googling for answers, but haven't had success yet. In the latest experiment I attempted to use an OUT variable and assign results to it, but apparently INTO cannot assign the values properly into an array and I haven't figured out how to make it work.

Please help me out. :) Much appreciated.

CREATE OR REPLACE FUNCTION assign_task(
  IN worker text,
  OUT id bigint[])
 RETURNS bigint[] AS
$BODY$BEGIN
 EXECUTE 'UPDATE queue
  SET status = ''In progress'', worker = $1
  WHERE status = ''New''
  RETURNING queueid'
 INTO id
 using worker;
END;$BODY$
LANGUAGE plpgsql VOLATILE
2

1 Answer 1

6

You are over complicating things. As you want to return multiple values you need to define the function as returns table or returns setof. I prefer returns table because it lets you also define the column names of the result.

You also don't need PL/pgSQL for this, a plain SQL function with an UPDATE statement is enough:

CREATE OR REPLACE FUNCTION assign_task(IN worker text)
  returns table (id bigint)
as
$BODY$
 UPDATE queue
  SET status = 'In progress', worker = $1
  WHERE status = 'New'
  RETURNING queueid;
$BODY$
LANGUAGE sql VOLATILE;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I was indeed over complicating things. :) I used setof because I could not find any way to create a function in pgAdmin that returns table. But setof is just fine for my purposes. Thanks again. :)
@KeeperB5: creating a function that returns a table is not different in pgAdmin than in any other client: just run the appropriate SQL statement

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.