使用 plpgsql 更新函数中的列

Update a column in a function using plpgsql

我正在 PostgreSQL 9.5 中编写触发器函数。当名为 action_flag 的列从 FALSE 更新为 TRUE 时,将调用一个函数。

如果 order_num 在某些 table 中,那么我希望继续从 FALSETRUE 的更新。

否则,如果 order_num 在其他 table 中,那么我想引发异常并阻止更新发生。

我需要帮助在 IF 语句中编写 UPDATEELSEIF 部分按预期运行。

CREATE OR REPLACE FUNCTION check_ingredient_availability()
RETURNS TRIGGER AS 
$Body$
BEGIN
    if (OLD.order_num IN ( SELECT  order_num
                   FROM    can_prep_m_orders )) THEN
        RAISE NOTICE 'This is a notice.';
        --UPDATE meal_order
        --SET actioned_flag=TRUE
        --WHERE order_num=OLD.order_NUM;

        --EXECUTE  'UPDATE  meal_order
            -- SET   actioned_flag=TRUE
             --WHERE     order_num=' 
             --USING OLD.order_num;
        RETURN NULL;
    ELSEIF (OLD.order_num IN ( SELECT  order_num
                        FROM    cannot_prep_m_orders )) THEN
        RAISE EXCEPTION 'Missing ingredients. Cannot prepare order number %.',
                OLD.order_num;
        RETURN NULL;
    ELSE
        RETURN NULL;
    END IF;
END;    
$Body$ LANGUAGE plpgsql;

使用EXISTS:

CREATE OR REPLACE FUNCTION check_ingredient_availability()
   RETURNS TRIGGER AS 
$func$
BEGIN
   IF EXISTS (
         SELECT 1 FROM can_prep_m_orders
         WHERE  order_num = NEW.order_num  -- NEW !?
         ) THEN
      RAISE NOTICE 'This is a notice.';

      -- do nothing, let original UPDATE proceed

      RETURN NEW;   -- let UPDATE proceed
   END IF;

   IF EXISTS (
         SELECT 1 FROM cannot_prep_m_orders
         WHERE  order_num = NEW.order_num  -- NEW!?
         ) THEN

      RAISE EXCEPTION 'Missing ingredients. Cannot prepare order number %.', NEW.order_num;
                                       -- I assume you want to mention the *new* order_num?
   END IF;

   RETURN NULL;  -- cancel original UPDATE in all other cases
END
$func$  LANGUAGE plpgsql;

相关:

  • PL/pgSQL checking if a row exists - SELECT INTO boolean

此外,在触发器中添加一个 WHEN 子句以 运行 这些检查

action_flag is updated from FALSE to TRUE

CREATE TRIGGER your_trigger_name
BEFORE UPDATE ON your_table
FOR EACH ROW 
WHEN (NEW.action_flag AND NOT OLD.action_flag)
EXECUTE procedure check_ingredient_availability();

相关:

  • Trigger with multiple WHEN conditions