【发布时间】:2020-09-07 18:01:56
【问题描述】:
我有表“orders”,我想在“tracking_code”列中添加值时自动更改“order_status”列(默认值为 null)但我的触发器函数更改了列“order_status”中的所有行我试图更改函数中的 if 语句,但没有成功。请帮我解决这个问题! 这是我的表“orders”:
id | order_status_id | tracking_code
----+-----------------+---------------
12 | 2 | 123456
9 | 2 |
6 | 2 |
7 | 2 |
10 | 2 |
8 | 2 |
11 | 2 |
和表“order_statuses”:
id | status
----+-------------
1 | QUEUE
2 | IN_PROGRESS
3 | IN_DELIVERY
4 | DELIVERED
5 | CANCELED
6 | RETURNED
这是我的触发器和函数:
CREATE or REPLACE FUNCTION status_function() RETURNS VOID AS $$
BEGIN
UPDATE public.orders SET order_status_id = public.order_statuses.id
FROM public.order_statuses
WHERE status = 'IN_DELIVERY';
END
$$ LANGUAGE plpgsql;
CREATE or REPLACE FUNCTION status_update() RETURNS TRIGGER AS $$
BEGIN
IF (old.tracking_code != new.tracking_code) THEN
PERFORM status_function();
RETURN new;
ELSE
RETURN old;
END IF;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER change_status
AFTER UPDATE
OF tracking_code
ON orders
FOR EACH ROW
EXECUTE PROCEDURE status_update();
【问题讨论】:
-
您的
status_function()是对orders的无条件更新。 -
我知道status_function是我的错!但你能澄清你的答案吗?
-
更新没有限制。它会将
orders中的所有行更新为order_status_id = 2。
标签: sql database postgresql triggers