【问题标题】:postgresql - trigger function with conditionpostgresql - 有条件的触发函数
【发布时间】:2020-05-01 23:24:35
【问题描述】:

我正在尝试创建带有条件的触发器。根据几何长度,我希望将属性“nom”(= name)写成大写或小写。

这是我所拥有的:

CREATE OR REPLACE FUNCTION public.test_upper_lower()  
RETURNS trigger AS  
    $BODY$
        BEGIN  
            NEW.dummy:= (ST_Length(new.geom)); 
            if (SELECT dummy FROM ligne_ligne)>100 
            then NEW.nom:= LOWER(nom) FROM ligne_ligne; 
            else NEW.nom:= UPPER(nom) FROM ligne_ligne;  
            end if;
            RETURN NEW;
        END;
    $BODY$
LANGUAGE plpgsql;  
DROP trigger IF EXISTS test_upper_lower on public.ligne_ligne;  
CREATE trigger test_upper_lower BEFORE INSERT OR UPDATE on public.ligne_ligne  
    FOR EACH ROW 
    EXECUTE PROCEDURE public.test_upper_lower();

这样我有一个“子查询返回多行”错误

基于这个论坛上的其他问题,我尝试使用 case 而不是 if 并在触发器本身中使用 when 不是函数,但两者都不起作用

有什么想法吗? 谢谢

【问题讨论】:

    标签: postgresql conditional-statements postgis plpgsql database-trigger


    【解决方案1】:

    您不需要(或实际上可以)使用SELECT 语句来访问插入行中的数据。

    SELECT dummy FROM ligne_ligne 部分从该表返回 所有 行 - 而不仅仅是来自与触发器相关的行。

    由于您只想检查刚刚计算的值,因此只需在此时使用new.dummy

    CREATE OR REPLACE FUNCTION public.test_upper_lower()  
    RETURNS trigger AS  
    $BODY$
    BEGIN  
      NEW.dummy:= ST_Length(new.geom); 
      if new.dummy > 100 then --<< no SELECT necessary
        NEW.nom:= LOWER(new.nom); --<< no "FROM", just access the value 
      else 
        NEW.nom:= UPPER(new.nom);  
      end if;
      RETURN NEW;
    END;
    $BODY$
    LANGUAGE plpgsql;  
    

    【讨论】:

      猜你喜欢
      • 2015-07-18
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 2011-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多