0

I have a PostgreSQL database and I want to make a script that replaces the data of one column of the table A with the data of an other tables column. I've written this PL/PgSQL function:

BEGIN;

    CREATE TEMPORARY TABLE tmp_table (id bigint PRIMARY KEY,
        registrationnumber character varying(255));
    INSERT INTO tmp_table
    select id,registrationnumber from tableB;

    for d in tmp_table loop
        update TABLEA set registrationnumber=d.id where 
            registrationnumber=d.registrationnumber;
        return next d;
    end loop;

END;

What is going wrong with my script?

0

1 Answer 1

2

There's no reason to do this in a loop - let the database engine do it for you.

 UPDATE tablea 
  SET registrationnumber = tableb.id
  FROM tableb
 WHERE tablea.registrationnumber = tableb.registrationnumber;

select * from tablea;

See this SQLFiddle:

http://sqlfiddle.com/#!1/1281b/1

Note that you are implicitly casting a varchar value to a bigint. If any of these varchar values don't cast correctly, the statement will fail.

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

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.