如何在postgres触发器中使用“IF语句”

时间:2010-06-16 19:58:29

标签: sql postgresql if-statement plpgsql

我有一个触发器功能,我只想触发某些INSERTS实例,在本例中为if do_backup = true。如果它在所有情况下都会触发,我会得到一个无限循环。这个逻辑对我来说似乎很简单,其余功能也可以。但触发器功能似乎没有注册我的条件并始终运行,即使在backup = true时也是如此。

CREATE OR REPLACE FUNCTION table_styles_backup() RETURNS
 TRIGGER AS $table_styles_backup$

 DECLARE
 ...
 do_backup  boolean;

    BEGIN
 SELECT backup INTO do_backup FROM table_details WHERE id=NEW.table_meta_id;

        IF (do_backup = true) THEN 

  ...


            INSERT INTO table_styles_versions 
   (
   ...
   )

  VALUES (
   ...
   );
 END IF;

    RETURN NULL;

    END;

$table_styles_backup$  LANGUAGE plpgsql;

CREATE TRIGGER table_styles_backup AFTER INSERT ON table_styles

FOR EACH ROW EXECUTE PROCEDURE table_styles_backup();

1 个答案:

答案 0 :(得分:4)

Per the documentation,您不需要在IF语句中显式测试布尔数据类型 - 它们默认测试为true,因此您可以使用:

IF do_backup THEN
  ...
  INSERT INTO table_styles_versions (...
ELSE
  -- omit this & the ELSE keyword if nothing needs to happen if do_backup is false
END IF;