我可以在PL / pgSQL函数中的赋值中使用SQL语句吗?

时间:2017-03-25 19:24:11

标签: sql postgresql plpgsql

我有这两个表(Encomenda和Informacaofaturacao),我正在尝试创建一个触发器,在插入Encomenda之前在Informacaofaturacao上插入一个新行,并将新的Informacaofaturacao行的ID放在Encomenda的新行上。 / p>

我做错了什么?

由于

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();

1 个答案:

答案 0 :(得分:3)

Postgres在分配时不接受修改SQL语句(INSERT,UPDATE或DELETE)的数据。 The documentation states:

  

...通过发送到主数据库引擎的SQL SELECT命令评估此类语句中的表达式。

您应该使用this form of executing a query with a single-row result代替。

此外,INSERT命令必须包含VALUES部分,它可以是:DEFAULT VALUES,VALUES(...)或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;