通过在 postgreSQL 中使用触发器将数据从一个 table 移动到另一个 table
Move Data from One table to other table by using trigger in postgreSQL
我需要在更新其中一列的值时将数据从一个 table 移动到另一个 table。我只想将更新的行移动到新的 table.
下面是我写的触发器。我的代码的问题是,它正在移动所有数据,而不仅仅是更新的行。谁能给个建议?
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();
我觉得你想要的逻辑是:
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()
;
理由:
您只想复制(部分)正在更新的行,因此不需要select
;您可以在行级触发器
中使用 new
访问当前行的值
触发器定义过滤等于 'CO'
的新 file_status
,因此函数 [=18] 中不需要 if
构造=]
这是一个 after
触发器,因此您可以 return null
- 结果无论如何都会被丢弃
我需要在更新其中一列的值时将数据从一个 table 移动到另一个 table。我只想将更新的行移动到新的 table.
下面是我写的触发器。我的代码的问题是,它正在移动所有数据,而不仅仅是更新的行。谁能给个建议?
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();
我觉得你想要的逻辑是:
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()
;
理由:
您只想复制(部分)正在更新的行,因此不需要
中使用select
;您可以在行级触发器new
访问当前行的值触发器定义过滤等于
'CO'
的新file_status
,因此函数 [=18] 中不需要if
构造=]这是一个
after
触发器,因此您可以 returnnull
- 结果无论如何都会被丢弃