开发者

Do I need to use a function to iterate over unique records for a mass update?

Running Postgres 7.4 (yeah we are upgrading) and I have a table where we are merging three fields into a new field if the field has value.

Example Data:

record_id | old_field_1 | old_field_2 | old_field_3 | new_field
+---------+-------------+-------------+-------------+----------+
12345     | blah        | foo         |             |            <-- new_field = foo
12346     |             |             | what        |            <-- new_field = what
12347     |             |             |             |            <-- new_field IS NULL
12348     | hello       |             |             |            <-- new_field = hello

So this works below for one record:

UPDATE db_table
SET new_field = CASE 
    WHEN old_field_3 IS NOT NULL THEN old_field_3
    WHEN old_field_2 IS NOT NULL THEN old_field_2
    WHEN old_field_1 IS NOT NULL THEN old_field_1
    ELSE new_field
END
WHERE record_id = 123456

And the next record would be

UPDATE db_table
SET new_field = CASE 
    WHEN old_field_3 IS NOT NULL THEN old_field_3
    WHEN old_field_2 IS NOT NULL THEN old_field_2
    WHEN old_field_1 IS NOT NULL THEN old_field_1
    ELSE new_field
END
WHERE record_id = 123457

old_field_# (1,2,3) are all different values. If old_field_3 IS NOT NULL use this value for the new_field, else check the next value. But each record has it's own unique value that needs to be updated

But I wanted to iterate over all the records in the database.

Trying a FOR loop but the syntax or proper usage I'm not implementing correctly. Just trying to get the SELECT working before trying to do the UPDATE syntax but having some issues.

FOR a_record IN SELECT * FROM db_table LOOP
    RAISE NOTICE 'record_id - %', a_record.record_id;
    RAISE NOTICE 'old_field_1     - %', a_recor开发者_C百科d.old_field_1; 
END LOOP;

What am I missing?


If i understand you correctly, if you want to do that combination for all records in a table, simply remove your where clause from your query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜