【问题标题】:Conditionally drop an insert in a before insert trigger without returning error有条件地在插入前触发器中删除插入而不返回错误
【发布时间】:2019-01-03 14:53:16
【问题描述】:

我在插入前触发器中有以下功能:

CREATE OR REPLACE FUNCTION schema.table_somefun()
RETURNS trigger AS
LANGUAGE 'plpgsql';
$BODY$
BEGIN
  IF NEW.col2 NOT NULL THEN
    NEW.col1 := CASE NEW.col1
                     WHEN '121432' THEN '321123'
                     ELSE <command> END CASE; --there should be a command aborting insertion without error or exception
  END IF;
  RETURN NEW;
END;
$BODY$

ELSE 语句应该中止插入。是否有一个命令可以删除查询而不告诉客户端并且保持表不变?

【问题讨论】:

  • RETURN NULL 取消插入。

标签: sql postgresql database-trigger


【解决方案1】:

随便用

RETURN NULL;

而不是

RETURN NEW;

取消该行的INSERT 并且什么都不做。

但是您不能在 SQL CASE 表达式内部执行 PL/pgSQL 语句。 (不要将SQL CASE 与类似的control structure CASE of PL/pgSQL 混淆!)
可能看起来像这样:

CREATE OR REPLACE FUNCTION schema.table_somefun()
  RETURNS trigger AS
$func$
BEGIN
   IF NEW.col2 NOT NULL THEN
      IF NEW.col1 = '121432' THEN  -- could also be plpgsql CASE ...
         NEW.col1 := '321123';
      ELSE
         RETURN NULL;
      END IF;
  END IF;
  RETURN NEW;
END
$func$  LANGUAGE plpgsql;

【讨论】:

    猜你喜欢
    • 2019-07-30
    • 2013-04-24
    • 2016-07-12
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多