简体   繁体   中英

Comparing values from different tables using triggers

so the problem is I have two tables and before inserting or updating the values on one table I have to check if the other table does not contain the new value I'm trying to insert/update like so:

CREATE TABLE categoriasimples(
    nome varchar(64) PRIMARY KEY REFERENCES categoria(nome) ON DELETE CASCADE);

CREATE TABLE supercategoria(
    nome varchar(64) PRIMARY KEY REFERENCES categoria(nome) ON DELETE CASCADE);

CREATE FUNCTION check_categoria_type_sup() RETURNS trigger AS $check_categoria_type_sup$
    BEGIN
        IF nome FROM categoriasimples WHERE (NEW.nome = CategoriaSimples.nome) IS NOT NULL THEN
            RAISE EXCEPTION 'Uma categoria nao pode ser super e simples ao mesmo tempo!';
        END IF;

        RETURN NEW;
    END;
$check_categoria_type_sup$ LANGUAGE plpgsql;

CREATE TRIGGER check_categoria_type_sup BEFORE INSERT OR UPDATE ON supercategoria FOR EACH ROW EXECUTE PROCEDURE check_categoria_type_sup();

CREATE FUNCTION check_categoria_type_simp() RETURNS trigger AS $check_categoria_type_simp$
    BEGIN
        IF nome FROM supercategoria WHERE (supercategoria.nome = NEW.nome) IS NOT NULL THEN
            RAISE EXCEPTION 'Uma categoria nao pode ser simples e super ao mesmo tempo!';
        END IF;

        RETURN NEW;
    END;
$check_categoria_type_simp$ LANGUAGE plpgsql;

CREATE TRIGGER check_categoria_type_simp BEFORE INSERT OR UPDATE ON categoriasimples FOR EACH ROW EXECUTE PROCEDURE check_categoria_type_simp();

I can insert values into one table but if I try to insert in the other table it says:

ERROR: invalid input syntax for type boolean: "bife" (Value that was in the other table) CONTEXT: PL/pgSQL function check_categoria_type_sup() line 3 at IF SQL state: 22P02

This is too long for a comment.

I'm pretty sure you can do what you want without using triggers. I would suggest that you investigate inheritance , which Postgres supports for tables.

You can just define a unique constraint on the parent table and not have to worry about trying to get two different tables to be in sync.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM