Postgresql 插入触发器以设置值 [英] Postgresql insert trigger to set value

查看:51
本文介绍了Postgresql 插入触发器以设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设在 Postgresql 中,我有一个表 T,其中一列是 C1.

Assume in Postgresql, I have a table T and one of its column is C1.

我想在向表中添加新记录时触发一个函数T.该函数应检查新记录中列 C1 的值,如果它为空/空,则将其值设置为 'X'.

I want to trigger a function when a new record is adding to the table T. The function should check the value of column C1 in the new record and if it is null/empty then set its value to 'X'.

这可能吗?

推荐答案

您需要触发器是正确的,因为为列设置默认值对您不起作用 - 默认值仅适用于 null 值,并不能帮助您防止空白值.

You are correct that you need a trigger, because setting a default value for the column won't work for you - default values only work for null values and don't help you in preventing blank values.

在 postgres 中创建触发器有几个步骤:

In postgres there are a couple of steps to creating a trigger:

步骤 1:创建一个返回类型 trigger 的函数:

Step 1: Create a function that returns type trigger:

CREATE FUNCTION my_trigger_function()
RETURNS trigger AS $$
BEGIN
  IF NEW.C1 IS NULL OR NEW.C1 = '' THEN
    NEW.C1 := 'X';
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql

第 2 步:创建一个触发器,在插入之前触发 ,它允许您在插入之前更改值,从而调用上述函数:

Step 2: Create a trigger that fires before insert, which allows you to change values befre they are inserted, that invokes the above function:

CREATE TRIGGER my_trigger
BEFORE INSERT ON T
FOR EACH ROW
EXECUTE PROCEDURE my_trigger_function()

大功告成.

请参阅以上在 SQLFIddle 上执行的代码,证明它可以正常工作!

See the above code executing on SQLFIddle demonstrating it working correctly!

您在评论中提到值 'X' 是从子查询中检索的.如果是这样,请更改相关行,例如:

You mention in a comment that the value 'X' is retrieved from a subquery. If so, change the relevant line so something like:

NEW.C1 := (select some_column from some_table where some_condition);

这篇关于Postgresql 插入触发器以设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆