Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use an SQL statement in assignment inside a PL/pgSQL function?

I've these two tables (Encomenda and Informacaofaturacao) and I'm trying to create a trigger to insert a new line on Informacaofaturacao before insert on Encomenda and put the ID of new line of Informacaofaturacao on new line of Encomenda.

What am I doing wrong?

Thanks

CREATE TABLE Encomenda
(
    EncomendaID SERIAL,
    ClienteID integer NOT NULL,
    MoradaFaturacaoID integer NOT NULL,
    MoradaEnvioID integer NOT NULL,
    InformacaofaturacaoID integer NULL,
    Data timestamp NOT NULL,
    Estado EstadoEncomenda NOT NULL DEFAULT 'Em processamento',
    CONSTRAINT PK_Encomenda PRIMARY KEY (EncomendaID)
)
;

CREATE TABLE Informacaofaturacao
(
    InformacaofaturacaoID SERIAL,
    MetodopagamentoID integer NULL,
    Portes real NULL,
    Iva real NULL,
    Total real NULL,
    CONSTRAINT PK_Informacaofaturacao PRIMARY KEY (InformacaofaturacaoID)
)
;

CREATE OR REPLACE FUNCTION insert_encomenda() 
RETURNS TRIGGER 
AS $$
BEGIN
    NEW.InformacaofaturacaoID := (INSERT INTO Informacaofaturacao RETURNING InformacaofaturacaoID);

    RETURN NEW;
END $$ LANGUAGE plpgsql;

CREATE TRIGGER insert_encomenda_trigger
BEFORE INSERT OR UPDATE ON Encomenda
FOR EACH ROW
    EXECUTE PROCEDURE insert_encomenda();
like image 335
agfac Avatar asked Apr 17 '26 20:04

agfac


1 Answers

Postgres doesn't accept a data modifying SQL statement (INSERT, UPDATE or DELETE) in assignment. The documentation states:

... the expression in such a statement is evaluated by means of an SQL SELECT command sent to the main database engine.

You should use this form of executing a query with a single-row result instead.

Also, INSERT command must have VALUES part, it can be: DEFAULT VALUES, VALUES(...) or query see the syntax in the documentation.

CREATE OR REPLACE FUNCTION insert_encomenda() 
RETURNS TRIGGER 
AS $$
BEGIN
    INSERT INTO Informacaofaturacao(InformacaofaturacaoID) 
    VALUES(DEFAULT) 
    RETURNING InformacaofaturacaoID
    INTO NEW.InformacaofaturacaoID;

    RETURN NEW;
END $$ LANGUAGE plpgsql;
like image 130
klin Avatar answered Apr 19 '26 11:04

klin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!