Search code examples
postgresqltriggersplpgsqlpostgresql-12

PostgreSQL trigger function syntax error help request


I haven't the slightest idea why postgres is complaining about the word 'INTO' after 'INSERT'. Does anyone know? FWIW I only created the body of the code, pgAdmin created the header and footer.

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 the error

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"

Solution

  • Declare statement should be before begin. So the correct definition will be like below:

    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;