I am having trouble with the plpsql below. What I am trying to do is:
- I have a table
namewith people's names - I am trying to write a PostgreSQL function that copies non-null columns from one person to another (as part of a larger merge)
- There are a lot of columns in the
nametable, and other tables where I want to do the same thing. - In order to limit the amount of code that needs to be written, I am trying to iterate through an array and generate dynamic SQL
However I cannot get this to work.
What I have so far is:
CREATE OR REPLACE FUNCTION test(first_id bigint, second_id bigint) RETURNS boolean AS $$
DECLARE
first_name name%ROWTYPE;
second_name name%ROWTYPE;
col_name VARCHAR(100);
sql_block VARCHAR(500);
BEGIN
SELECT * INTO first_name FROM name WHERE person_id = first_id;
SELECT * INTO second_name FROM name WHERE person_id = second_id;
FOREACH col_name IN ARRAY ARRAY['column1', 'column2', 'column3', 'column4']
LOOP
---- The follow line is not working and keeps giving a syntax error
EXECUTE 'if (first_name .' || col_name || ' IS NULL and second_name.' ||
col_name || ' IS NOT NULL) THEN UPDATE name set ' || col_name ||
' = second_name.' || col_name || ' where name.id = first_name.id; END IF;';
END LOOP;
RETURN TRUE;
END;
$$ LANGUAGE plpgsql;