【问题标题】:how to make a trigger before insert in PostgreSQL?如何在 PostgreSQL 中插入之前触发?
【发布时间】:2022-01-19 23:41:51
【问题描述】:

我正在尝试编写一个插入前触发器,

我的桌子应该是这样的

id cl.2 cl.3 cl.4
a1 1 null l
a1 2 f m
a1 3 t z
a1 4 b q
a1 5 k e
a1 6 d null

如果 new.cl.2 = 1 那么 cl.3 必须为 null 其他方式应该有一个值。 我必须把列放在 NUTT NULL 中吗??

CREATE FUNCTION check_tijdsteppen()
RETURNS trigger AS
$BODY$
DECLARE
BEGIN    
    IF EXISTS( new.cl.2 = '1' )  
        then new.cl.3 is null, ;
    END IF;
    
    RETURN NEW;
    
END;
$BODY$
LANGUAGE plpgsql;
    
CREATE TRIGGER check_tijdsteppen_trigger
    BEFORE INSERT
    ON my_table 
        FOR EACH ROW
        EXECUTE PROCEDURE check_tijdsteppen();

对于 cl.4,我不知道 cl.2 中每个 id 的最后一个数字应该是什么
但我想我可以通过触发说如果

new.cl.2=test.cl.2 + 1 and test.cl.4 is null and new.cl4=test.cl4

那么我必须出去。这是个好主意吗 ?所以只有当列中没有值时才可能为空 其他方式我无法插入新值 任何提示!

【问题讨论】:

  • 假设您在cl.2 中的数字始终从“1”开始,您可以使用简单的CHECK CONSTRAINT 来确保那些行在cl.3 中具有“NULL”,而在@ 中具有“1” 987654327@。不需要触发器来做到这一点。对于第二部分(确保cl.4 中的最后一行有“NULL”),您肯定需要一个触发器。
  • new.cl.3 is null, ; 应该是new.cl.3 = null ;

标签: sql postgresql triggers


【解决方案1】:
create or replace function check_tijdsteppen()
returns trigger
language plpgsql
as $function$
begin

    if (new.field1 = '1') then  
        new.field2 = null;
        new.field3 = 'none';
        new.field4 = 10;
    end if;
    
    return new;
    
end;
$function$
;

【讨论】:

    猜你喜欢
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 2017-08-15
    • 2018-04-17
    • 1970-01-01
    相关资源
    最近更新 更多