使用递归和 IF 语句创建触发器和触发器函数

CREATE TRIGGER AND TRIGGER FUNCTION WITH RECURSIVE AND IF STATEMENT

我想创建一个在我的数据库中插入之前调用的触发器。

触发函数检查一个条件。

要检查我的情况,我需要 RECURSIVITY,这就是我所做的:

CREATE OR REPLACE FUNCTION trigger_check_relation()
  RETURNS TRIGGER AS

$$BEGIN

    WITH RECURSIVE parent_list AS (

      SELECT relation.parent
      FROM relation
      WHERE relation.child = 9817

      UNION

      SELECT r.parent FROM relation r
        JOIN parent_list on parent_list.parent = r.child
    )
    SELECT name FROM component WHERE _id in (SELECT parent FROM parent_list);

    IF 9817 in (SELECT _id FROM component WHERE _id in (SELECT parent FROM parent_list))
        THEN RETURN OLD;
     ELSE 
        RETURN NEW;
     END IF;

END;$$ LANGUAGE plpgsql;

我可以创建我的触发器和函数,但是当我 运行 它有 :

ERROR: query has no destination for result data HINT: If you want to discard the results of a SELECT, use PERFORM instead. CONTEXT: PL/pgSQL function trigger_check_relation() line 3 at SQL statement SQL state: 42601

你能帮我理解并解决这个问题吗?

函数中有两个语句:第一个是“WITH RECURSIVE parent_list … SELECT name FROM …”但是它没有对结果做任何事情,比如将它赋值给一个变量。

我认为您可能需要将 WITH 子句移动到条件中:

IF 9817 in (
  WITH RECURSIVE parent_list AS (

    SELECT relation.parent
    FROM relation
    WHERE relation.child = 9817

    UNION

    SELECT r.parent FROM relation r
      JOIN parent_list on parent_list.parent = r.child
  )
  SELECT _id FROM component
    WHERE _id in (SELECT parent FROM parent_list)
)
…