AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 322759
Accepted
Hasan Can Saral
Hasan Can Saral
Asked: 2023-01-31 02:41:15 +0800 CST2023-01-31 02:41:15 +0800 CST 2023-01-31 02:41:15 +0800 CST

A tabela ORA-04091 está mutando, o gatilho/função pode não vê-lo quando em cascata, funciona de outra forma

  • 772

Tenho as duas tabelas a seguir:

CREATE TABLE entries
(
    id                  NUMBER(20, 0)                           NOT NULL PRIMARY KEY,        
    first_name          VARCHAR2(512) DEFAULT NULL              NULL,
    last_name           VARCHAR2(512) DEFAULT NULL              NULL,
    last_updated_at     TIMESTAMP     DEFAULT NULL              NULL
);

CREATE TABLE entry_details
(
    id       NUMBER(20, 0)              NOT NULL PRIMARY KEY,
    entry_id NUMBER(20, 0)              NOT NULL,
    value    VARCHAR2(512) DEFAULT NULL NULL,
    CONSTRAINT fk_details_entry_id FOREIGN KEY (entry_id) REFERENCES entries(id) ON DELETE CASCADE
);

Preciso atualizar last_updated_atsempre que houver uma alteração/exclusão na tabela entriesor entry_details, então tenho esta trigger:

CREATE OR REPLACE TRIGGER detail_delete_trigger
    BEFORE DELETE
    ON entry_details
    FOR EACH ROW
BEGIN
    UPDATE entries
    SET last_updated_at = CURRENT_TIMESTAMP
    WHERE id = :OLD.entry_id;
END;

Isso funciona bem quando há uma exclusão entry_detailsdiretamente. No entanto, recebo o ORA-04091: entries table is mutatingerro quando há exclusão da entriestabela que se propaga para entry_details. Eu tentei:

  1. PRAGMA AUTONOMOUS_TRANSACTIONSque cede aORA-00060: deadlock detected while waiting for resource
  2. Usando uma AFTER DELETEtrigger, que deu novamente, a tabela está com erro de mutação
  3. Não foi possível usar INSTEAD OF DELETEporque não é para tabelas conformeORA-25002: cannot create INSTEAD OF triggers on tables
  4. Eu removi CASCADEe adicionei o seguinte gatilho:

ALTER TABLE entry_details DROP CONSTRAINT fk_details_entry_id;
ALTER TABLE entry_detailsADD CONSTRAINT fk_details_entry_idFOREIGN KEY (entry_id) REFERENCES entries(id);

CREATE OR REPLACE TRIGGER aml_entries_delete_trigger
    BEFORE DELETE -- or AFTER DELETE, same result
    ON entries
    FOR EACH ROW
BEGIN
    DELETE FROM entry_details WHERE entry_id = :OLD.id;
END;

Mas ainda recebo o ORA-04091 table is mutating trigger/function may not seeerro. Como faço para superar isso?

oracle
  • 1 1 respostas
  • 35 Views

1 respostas

  • Voted
  1. Best Answer
    miracle173
    2023-01-31T09:49:07+08:002023-01-31T09:49:07+08:00

    Talvez você possa usar um sinalizador que é definido quando uma linha na tabela pai é excluída e desativada após suas exclusões. Você pode tentar o seguinte código:

    CREATE TABLE entries
    (
        id                  NUMBER(20, 0)                           NOT NULL PRIMARY KEY,        
        first_name          VARCHAR2(512) DEFAULT NULL              NULL,
        last_name           VARCHAR2(512) DEFAULT NULL              NULL,
        last_updated_at     TIMESTAMP     DEFAULT NULL              NULL
    );
    
    CREATE TABLE entry_details
    (
        id       NUMBER(20, 0)              NOT NULL PRIMARY KEY,
        entry_id NUMBER(20, 0)              NOT NULL,
        value    VARCHAR2(512) DEFAULT NULL NULL,
        CONSTRAINT fk_details_entry_id FOREIGN KEY (entry_id) REFERENCES entries(id) ON DELETE CASCADE
    );
    
    create or replace package trigger_state
    as
        cascading BOOLEAN := FALSE;
    end;
    /
    
    
    CREATE OR REPLACE TRIGGER entry_before_delete_trigger
        BEFORE DELETE
        ON entries
        FOR EACH ROW
    BEGIN
        trigger_state.cascading := TRUE;
    END;
    /
    
    CREATE OR REPLACE TRIGGER entry_after_delete_trigger
        AFTER DELETE
        ON entries
        FOR EACH ROW
    BEGIN
        trigger_state.cascading := FALSE;
    END;
    /
    
    
    CREATE OR REPLACE TRIGGER detail_delete_trigger
        BEFORE DELETE
        ON entry_details
        FOR EACH ROW
    BEGIN
        IF NOT trigger_state.cascading THEN
            UPDATE entries
            SET last_updated_at = CURRENT_TIMESTAMP
            WHERE id = :OLD.entry_id;
            END IF;
    END;
    /
    

    com dados de teste

    insert into entries(id) values(1);
    insert into entries(id) values(2);
    insert into entries(id) values(3);
    insert into entries(id) values(4);
    insert into entry_details(id,entry_id) values(1,1);
    insert into entry_details(id,entry_id) values(2,1);
    insert into entry_details(id,entry_id) values(3,3);
    insert into entry_details(id,entry_id) values(4,3);
    insert into entry_details(id,entry_id) values(5,3);
    insert into entry_details(id,entry_id) values(6,4);
    insert into entry_details(id,entry_id) values(7,4);
    commit;
    

    Agora tente deletar

    delete from entry_details where id=6;
    commit;
    

    Isso atualizará a linha pai.

    • 1

relate perguntas

  • Backups de banco de dados no Oracle - Exportar o banco de dados ou usar outras ferramentas?

  • ORDER BY usando prioridades personalizadas para colunas de texto

  • Interface sqlplus confortável? [fechado]

  • Como encontrar as instruções SQL mais recentes no banco de dados?

  • Como posso consultar nomes usando expressões regulares?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve