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

查看:523
本文介绍了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天全站免登陆