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

I have a trigger that before every update on hundreds of tables it inserts into a table with the same name and the _hv suffix a copy of the record being updated to maintain a kind of historical updates.

So when there is an update in my_example table. The table my_example_hv that has the same fields in the beginning of the table and some extra fields in the end (update timestamps, update user, etc). Using this line it works perfectly:

EXECUTE 'INSERT INTO '|| TG_RELNAME ||'_hv SELECT  ($1).*' USING NEW;

Ok the problem comes when I need to insert a new field to the main table. I can add the new field too to the _hv table but I can't reorder the fields in my postgresql version (8.4). I know it's obsolete but I can't upgrade it right now because I have some old software that needs that version of postgresql.

So what would be the code to insert the record to th _hv table having some field now in different order but with the same column names?

share|improve this question
    
Erm, why not just list the column names? – Colin 't Hart Mar 24 '15 at 9:14
    
because I need a trigger that works for the hundreds of tables I've got, so I can avoid having to create hundreds of triggers – Egidi Mar 24 '15 at 11:05
    
Listing the column names is probably the only way you're going to get this to work. I'd query metadata to generate column lists or even entire triggers. – Colin 't Hart Mar 24 '15 at 11:30
1  
If hstore(NEW.*) works with 8.4, you might use that to reconstruct a dynamic insert with column names in any order as hstore keys, and column values as corresponding hstore values. – Daniel Vérité Mar 24 '15 at 14:38
    
@Daniel Vérité could ypu please write an answer so I can accept it? Do I have to hstore(NEW.*) to convert it in key=>value pairs but how do I insert those records in a new table in the correct order? – Egidi Mar 25 '15 at 11:24

Your Answer

 
discard

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

Browse other questions tagged or ask your own question.