postgresql - `instead of update` trigger: How to distinguish when user provides new value for the column and when does not?
问题描述
Inside the trigger NEW.field
value is always has <some value>
despite on that column appears on SET
list of UPDATE statement or does not:
UPDATE test SET name = 'abc', field = <some value>;
UPDATE test SET name = 'abc';
For both queries in trigger I will get field
with <some value>
.
Is there a way to distinguish these two queries from inside trigger?
解决方案
我认为您可以将新值与旧值进行比较。如果不同,您就知道该字段已设置。
除非您想捕获该字段的更新时间,否则即使该字段值没有更改,我也会认为这会捕获它。
CREATE OR REPLACE FUNCTION test_update_trigger()
RETURNS trigger AS
$BODY$
BEGIN
if (OLD.field is null and NEW.field is not null or
OLD.field is not null and NEW.field is null or
OLD.field != NEW.field) then
-- do something
end if;
return NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
推荐阅读
- django - Django:在模型级别而不是列级别应用验证器
- cypress - 赛普拉斯测试通过了单个表单输入字段,但忽略了以下输入字段
- python - 从嵌入列中的列表中提取元素
- python - 我的 python 气泵代码有什么问题?
- ios - 如何在 Swift 中向自定义 DateComponent 添加分钟
- python - 将列表中的唯一元素附加到新列表
- wordpress - AMP 上的 Google 表单是否需要 HTTPS?
- extreact - Sencha extJs/exreact 6/7 Tree 获取选中记录
- python - 排序算法不会产生正确的输出
- c++ - 我试图让它从文件中打印一些东西,它正在打印这些奇怪的东西