简体   繁体   中英

Move Data from One table to other table by using trigger in postgreSQL

I have the requirement to move data from one table to another table when the value of one of the columns is updated. And I just want to move the updated row to the new table.

Below is my trigger that I have written. The issue with my code is, that it is moving all the data and not just the row which was updated. Can anyone give a suggestion?

  create or replace function moveToAC1ControlHist() 
  returns trigger as $$ 
  begin if NEW.file_status='CO' 
  then
  insert into ac1_control_hist (file_status,identitifier) 
  (
   select file_status,identitifier      
    from
    ac1_control where new.FILE_STATUS = 'CO'
  );
  end if;
  return new;
  end;
  $$ language plpgsql;


  create  TRIGGER AC1_CONTROL_TRIGGER AFTER update of file_status ON AC1_CONTROL
  FOR EACH ROW when (new.file_status ='CO')EXECUTE PROCEDURE moveToAC1ControlHist();

I think the logic you want is:

create or replace function moveToAC1ControlHist() 
returns trigger as 
$$ 
begin
    insert into ac1_control_hist (file_status,identitifier) 
    values (new.file_status, new.identitifier);
    return null;
end;
$$ language plpgsql;

create trigger ac1_control_trigger 
    after update of file_status on ac1_control
    for each row 
    when (new.file_status ='co')
    execute function movetoac1controlhist()
;

Rationale:

  • you just want to copy (part of) the row being updated, so there is no need to select ; you can access the values of the current row with new in a row-level trigger

  • the trigger definition filters on new file_status that is equal to 'CO' , so there is no need for a if construct in the function

  • this is an after trigger, so you can just return null - the result is discarded anyway

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM