【发布时间】:2021-09-08 03:22:54
【问题描述】:
我想要实现的是,当我执行 UPDATE 语句时,我希望 TRIGGER 更新具有 insurance_team = 'professional' 和 expiration_date = current_date 的每一行>,只需将到期年份+1。
我当前的 TRIGGER 函数虽然更新了整个列。
表格
CREATE TABLE insurance_premiums (
contract_code text NOT NULL,
insurance_team text NOT NULL,
starting_date date NOT NULL,
expiration_date date NOT NULL,
contract_cost float8 NOT NULL,
vehicle_contract text NOT NULL,
customer_contract text NOT NULL,
driver_contract text NOT NULL,
CONSTRAINT insurance_premiums_pkey PRIMARY KEY (contract_code)
);
触发器
create trigger update_contract after
update
on
public.insurance_premiums for each row execute function new_date()
触发函数
CREATE OR REPLACE FUNCTION public.new_date()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
if old.insurance_team = 'professional' then
if old.expiration_date = CURRENT_DATE then
new.expiration_date = old.expiration_date + integer '365';
update insurance_premiums set expiration_date = new.expiration_date;
end if;
end if;
return new;
END;
$function$
;
更新示例
UPDATE insurance_premiums
SET contract_cost = 736.33
WHERE contract_code = 'EI-36653';
插入上面的例子:
INSERT INTO insurance_premiums (contract_code, insurance_team, starting_date, expiration_date, contract_cost, vehicle_contract, customer_contract, driver_contract)
VALUES('EI-36653', 'professional', '2019-03-31', '2021-06-24', 12736.3, 'Sprinter', 'Antoine Burgise', 'Prudence Lacer');
旁注:上面的更新语句只是一个测试触发器的例子。
【问题讨论】:
-
丢失
update insurance_premiums ...部分。您已经为该行设置了new.expiration_date。您的UPDATE没有WHERE将其限制为特定行,无论如何都是多余的。 -
@AdrianKlaver 如果我从函数中删除更新查询,那么它不会更新任何内容。对于 where 部分,我认为 if 语句已经涵盖了我。
-
使用
BEFORE UPDATE触发器。
标签: sql postgresql