PostgreSQL 触发器函数语法错误求助

PostgreSQL trigger function syntax error help request

我完全不知道为什么 postgres 在 'INSERT' 之后抱怨 'INTO' 这个词。有人知道吗? FWIW 我只创建了代码的主体,pgAdmin 创建了页眉和页脚。

CREATE FUNCTION public.tf_test()
    RETURNS trigger
    LANGUAGE 'plpgsql'
     NOT LEAKPROOF
AS $BODY$BEGIN
  DECLARE targetid orderpayment.id%TYPE;

  INSERT INTO
    orderpayment(currencycode,tableorderid,payment,tip,paymentprocessor)
  VALUES
    (NEW.currency,NEW.orderid,NEW.amount,NEW.tip,1)
  RETURNING id INTO targetid;
  
  NEW.orderpayment = targetid;

  RETURN NEW;
END$BODY$;

returns 错误

ERROR: syntax error at or near "INTO"
LINE 8: INSERT INTO
^
CONTEXT: invalid type name "INTO
orderpayment(currencycode,tableorderid,payment,tip,paymentprocessor)
VALUES
(NEW.currency,NEW.orderid,NEW.amount,NEW.tip,1)
RETURNING id INTO targetid"

Declare语句应该在begin之前。所以正确的定义如下:

CREATE or REPLACE FUNCTION public.tf_test()
    RETURNS trigger

    NOT LEAKPROOF AS 

$BODY$ 
    DECLARE 
     targetid orderpayment.id%TYPE;
   
    BEGIN
  

    INSERT INTO
       orderpayment(currencycode, tableorderid, payment, tip, paymentprocessor)
    VALUES
       (NEW.currency,NEW.orderid,NEW.amount,NEW.tip,1)
    RETURNING id INTO targetid;
  
    NEW.orderpayment = targetid;

    RETURN NEW;
   END;
$BODY$
LANGUAGE plpgsql;