Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Say I have a table defined as following:

CREATE TABLE my_tbl (
    id  bigint,
    a1  bigint[],
    a2  bigint[]
);

I would like to create a stored procedure to append values to a1 and a2. Is this the right way to proceed or is there a simpler way?

CREATE OR REPLACE FUNCTION append(
        iid  bigint,
        next_a1  bigint,
        next_a2  bigint)
DECLARE
    r       "my_tbl";
    tmp_a1  bigint[]; 
    tmp_a2  bigint[]; 
BEGIN
    FOR r IN SELECT * FROM "my_tbl"
              WHERE r."id" = iid
                FOR UPDATE
        LOOP
            tmp_a1 := r.a1 || next_a1;
            tmp_a2 := r.a2 || next_a2;
            UPDATE my_tbl SET ( "a1", "a2" ) = ( tmp_a1, tmp_a2 )
             WHERE "id" = iid;
        END LOOP;
END; $$
LANGUAGE plpgsql;

I am on Postgresql 9.2.

share|improve this question
up vote 1 down vote accepted

You can simply do

UPDATE my_tbl 
   SET (a1, a2) = (a1 || 123465, a2 || 132456789)
 WHERE id = 321;

To obtain a function, you simply have to replace the integer constants with the parameters. You can safely do it in a query language (aka SQL) function, no need for pl/pgsql at all.

share|improve this answer
    
Many thanks !!! – JVerstry May 20 '15 at 16:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.