表“updatero”上的更新或删除违反了表“filme”

时间:2016-08-29 15:35:10

标签: postgresql

我需要使用函数删除genro表的类型。但是当我创建函数并运行“select * from delet”时,显示消息:

ERROR: update or delete on table "genero" violates foreign key constraint "fk_genero_filme" on table "filme"
DETAIL: Key (id) = (1) is still referenced from table "movie".

我的表结构:

create table genero(
    id numeric(5) not null,
    nome varchar(100), 
    constraint genero_pkey primary key (id)
);

create table filme(
    id numeric(5) not null,
    nome varchar(100),
    duracao varchar(100),
    sinopse varchar(2000),
    genero numeric(5),
    data timestamp, 
    constraint pk_genero primary key (id), 
    constraint fk_genero_filme foreign key (genero) references genero (id)
);

删除功能:

CREATE OR REPLACE FUNCTION delet (id numeric(5))
RETURNS VOID AS
$$
BEGIN
    DELETE FROM genero;
END;
$$
LANGUAGE 'plpgsql' VOLATILE COST 100;

函数调用:

Select delet(6);

1 个答案:

答案 0 :(得分:0)

好的,代码存在一些问题。

首先,delet函数删除所有行,因为没有WHERE子句。它应该更像是:

CREATE OR REPLACE FUNCTION delet(_id numeric)
    RETURNS void AS
$BODY$
BEGIN
    DELETE FROM genero WHERE id = _id;
END;
$BODY$
    LANGUAGE plpgsql VOLATILE COST 100;

其次,fk_genero_filme约束(在错误中报告)具有默认行为 - NO ACTION。这意味着如果您至少有一部电影引用一种类型,则无法删除此特定类型。如果您期望DELRE on genre也将删除此类型的所有电影,您应该使用ON DELETE CASCADE:

ALTER TABLE filme
    DROP CONSTRAINT fk_genero_filme;
ALTER TABLE filme
    ADD CONSTRAINT fk_genero_filme
        FOREIGN KEY (genero)
        REFERENCES genero (id) MATCH SIMPLE
        ON UPDATE CASCADE ON DELETE CASCADE;

最后,出于性能原因,您应该将ID定义为整数而不是数字。