[英]Trigger function that Updates some columns after update of a specific column
I have the table Ticketsforsale: 我有售票表:
Ticketsforsale(ticket_id, starting_date, price)
I need to create a trigger function which , in case of update on "starting_date" , will replace the old "starting_date" with the updated one in addition to lowering the "price" by 20% . 我需要创建一个触发函数,如果在“ starting_date”上进行更新,则除了将“ price”降低20%之外,还将用更新后的函数替换旧的“ starting_date”。
The trigger function I've came up with so far is the following : 到目前为止,我想到的触发函数如下:
create or replace function automatic_update()
RETURNS TRIGGER AS $$
begin
IF new.starting_date != ticketsforsale.starting_date
THEN old.starting_date = new.starting_date ,
ticketsforsale.price = ticketsforsale.price * (20/100) ;
END IF ;
RETURN NEW ;
END ;
$$
LANGUAGE plpgsql ;
CREATE TRIGGER automation
BEFORE INSERT OR UPDATE ON public.ticketsforsale
FOR EACH ROW EXECUTE PROCEDURE automatic_update()
The trigger function code is running properly without any errors. 触发功能代码正常运行,没有任何错误。
But when I update the value of a "starting_date" column and try to save the change , I get the following error : 但是,当我更新“ starting_date”列的值并尝试保存更改时,出现以下错误:
Missing FROM-clause entry on table 'ticketsforsale' LINE 1 :SELECT new.starting_date != ticketsforsale.starting_date * QUERY: SELECT new.starting_date != ticketsforsale.starting_date CONTEXT: PL/pgsql function automatic_update() line 3 at IF
表'ticketsforsale'上缺少FROM子句条目LINE 1:SELECT new.starting_date!= ticketsforsale.starting_date *查询:SELECT new.starting_date!= ticketsforsale.starting_date背景:PL / pgsql函数IF的第3行
I've tinkered with the function pretty much . 我已经对该功能进行了很多修改。 However I didn't seem to get it right , thanks .
但是,我似乎没有做好,谢谢。
You can use the old
pseudo record to access the values before the update. 您可以使用
old
伪记录来访问更新前的值。 It doesn't make sense to set old
values though. 设置
old
值没有任何意义。 And such a trigger makes no sense for INSERT
as there is no old value that can change here. 这样的触发器对于
INSERT
没有意义,因为这里没有可以更改的旧值。 And you're not lowering the price by 20% you set it to 20%. 您不会将价格降低20%,而是将其设置为20%。
Something like the following should work as you want. 像下面这样的东西应该可以工作。
CREATE OR REPLACE FUNCTION automatic_update()
RETURNS TRIGGER
AS
$$
BEGIN
IF new.starting_date <> old.starting_date THEN
new.price := old.price * .8;
END IF;
RETURN new;
END;
$$
LANGUAGE plpgsql;
CREATE TRIGGER automation
BEFORE UPDATE
ON public.ticketsforsale
FOR EACH ROW
EXECUTE PROCEDURE automatic_update();
You could also move the condition to the triggers WHEN
. 您也可以将条件移动到触发器
WHEN
。
CREATE OR REPLACE FUNCTION automatic_update()
RETURNS TRIGGER
AS
$$
BEGIN
new.price := old.price * .8;
RETURN new;
END;
$$
LANGUAGE plpgsql;
CREATE TRIGGER automation
BEFORE UPDATE
ON public.ticketsforsale
FOR EACH ROW
WHEN (new.starting_date <> old.starting_date)
EXECUTE PROCEDURE automatic_update();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.