sql - Exclude updated record from trigger function
问题描述
I have a table with a column named priority. I created a trigger function that fires after update. I want the function to change the values of the rest of the rows' priority column. For example I have 10 rows and each row has a single value ranging from 1-10, I then want to change the priority of row 10 to 1, then add 1 to the rest of the rows.
I've tried to change the query in many ways and add more/less logic to the function, but I am stuck.
CREATE FUNCTION reorder_priority() RETURNS TRIGGER AS $$
BEGIN
CASE TG_OP
WHEN 'UPDATE' THEN
UPDATE
link
SET
priority = priority + 1
WHERE
link.priority >= NEW.priority AND
NOT link.priority > OLD.priority;
END CASE;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
This function was able to do this, but it seems to trigger twice, adding 1 to every single row again, leaving me with 10 rows, but priority ranging from 2-11.
解决方案
I figured it out..
Just had to change the comparison to exclude updating the value of OLD.priority, return NEW, and also change the trigger to run BEFORE and not AFTER
BEGIN
CASE TG_OP
WHEN 'UPDATE' THEN
UPDATE
link
SET
priority = priority + 1
WHERE
link.priority >= NEW.priority AND
NOT link.priority >= OLD.priority;
END CASE;
RETURN NEW;
END;
推荐阅读
- java - 如何将值添加到哈希表Java中的值数组中
- python - 在网页抓取期间,我收到以下错误“无效语法(
,第 11 行)”在 python 3.4.4 中写入 print commad - hadoop - 在不同的用户上使用 Sqoop?
- c# - 特殊字符之前的单词边界匹配失败
- mysql - 如何更新时间戳
- spring-boot - Gradle java.lang.OutOfMemoryError:元空间
- caching - 构造唯一性由 6 个属性定义的缓存键的最佳方法
- laravel - 条件不适用于条件
- prolog - 用于检查列表中的变量名的内置谓词
- linux - 在 Dockerfile 中按回车