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 / coding / Perguntas / 76936459
Accepted
bernie
bernie
Asked: 2023-08-20 02:09:53 +0800 CST2023-08-20 02:09:53 +0800 CST 2023-08-20 02:09:53 +0800 CST

Oracle sqlldr: as restrições não são reativadas após o término do carregamento do lote

  • 772

Tenho a seguinte tabela em meu banco de dados Oracle (19c):

CREATE TABLE debtors (
    bankruptID NUMBER NOT NULL,
    category VARCHAR2(50) NOT NULL,
    lastname VARCHAR2(100),
    firstname VARCHAR2(80),
    birthdate DATE,
    birthplace VARCHAR2(100),
    constraint DEBTORS_PK PRIMARY KEY (bankruptID));
    
ALTER TABLE debtors ADD CONSTRAINT debtors_fk0 FOREIGN KEY (category) REFERENCES categories(BankruptCategory);
    

Possui uma chave primária e uma chave estrangeira para outra tabela. Para esta tabela (devedores), desejo importar dados de um arquivo csv usando sqlldr. Aqui estão os arquivos ctl e *par *:

OPTIONS (SKIP=1)
LOAD DATA
CHARACTERSET CL8MSWIN1251
INTO TABLE myschema.debtors
REENABLE DISABLED_CONSTRAINTS EXCEPTIONS EXCEPT_TABLE
FIELDS TERMINATED BY '^'
TRAILING NULLCOLS
(
bankruptID,
category,
lastname,
firstname,
birthdate date 'YYYY-MM-DD HH24:MI:SS',
birthplace
)
userid=username/password@mydb
control=debtors.ctl
log=debtors.log
bad=debtors.bad
data=debtors.csv
direct=true

Depois de concluir a tarefa, o arquivo de log informa o seguinte:

Restrição de integridade referencial/informações de gatilho: as restrições NULL, UNIQUE e PRIMARY KEY não são afetadas.

A restrição mychema.DEBTORS.DEBTORS_FK0 foi desativada e atualizada antes do carregamento. O(s) seguinte(s) índice(s) na tabela mychema.DEBTORS foram processados: index mychema.DEBTORS_PK carregado com sucesso com 896 chaves

A tabela mychema.DEBTORS não possui tabela de exceção de restrição. Nenhuma restrição CHECK, REFERENTIAL foi reativada após o carregamento.

E a chave estrangeira (debtors_fk0) fica desativada. Como você pode ver no arquivo *ctl *, tenho a cláusula REENABLE, mas parece não estar funcionando. Você poderia me ajudar a entender qual é o problema? Eu quero que ele reative a restrição automaticamente

Criei uma tabela EXCEPT_TABLE para armazenar todas as exceções, mas não adiantou

oracle
  • 1 1 respostas
  • 27 Views

1 respostas

  • Voted
  1. Best Answer
    Littlefoot
    2023-08-20T03:49:30+08:002023-08-20T03:49:30+08:00

    Tudo é como esperado. Se você verificar o status da restrição, verá que está ATIVADO, mas NÃO VALIDADO - não pode ser se houver linhas que violam a restrição de chave estrangeira.


    Exemplo 1 : o que acontece quando tudo está bem?

    Tabelas de amostra:

    SQL> create table except_table
      2    (row_id     rowid,
      3     owner      varchar2(128),
      4     table_name varchar2(128),
      5     constraint varchar2(128)
      6    );
    
    Table created.
    

    Duas categorias (22, 33) - AMBAS serão usadas durante o carregamento de dados, o que significa que a restrição de chave estrangeira não será violada:

    SQL> create table category
      2    (id_cat number primary key);
    
    Table created.
    
    SQL> insert into category values (22);
    
    1 row created.
    
    SQL> insert into category values (33);
    
    1 row created.
    
    SQL> create table test
      2    (id_test     number constraint pk_t primary key,
      3     id_cat      number constraint fk_tc references category,
      4     debit       number
      5    );
    
    Table created.
    
    SQL>
    

    Arquivo de controle:

    load data
    infile *
    replace
    into table test
    reenable disabled_constraints exceptions except_table
    fields terminated by '|'
    trailing nullcols
    ( id_test,
      id_cat,
      debit
    )
    
    begindata
    1|22|456
    2|33|777
    

    Carregando sessão: com caminho direto, o Oracle desabilita automaticamente as restrições conforme descrito na documentação.

    SQL>  $sqlldr scott/tiger@pdb1 control=test15.ctl log=test15.log direct=true
    
    SQL*Loader: Release 21.0.0.0.0 - Production on Sat Aug 19 21:38:05 2023
    Version 21.3.0.0.0
    
    Copyright (c) 1982, 2021, Oracle and/or its affiliates.  All rights reserved.
    
    Path used:      Direct
    
    Load completed - logical record count 2.
    
    Table TEST:
      2 Rows successfully loaded.
    
    Check the log file:
      test15.log
    for more information about the load.
    
    SQL>
    

    Arquivo de log diz:

    Referential Integrity Constraint/Trigger Information:
    NULL, UNIQUE, and PRIMARY KEY constraints are unaffected.
    
    Constraint TEST.FK_TC was disabled and novalidated before the load.
    The following index(es) on table TEST were processed:
    index SCOTT.PK_T loaded successfully with 2 keys
    TEST.FK_TC was re-enabled.
    
    Table TEST has constraint exception table EXCEPT_TABLE.
    Constraint TEST.FK_TC was validated
    

    Resultado:

    SQL> select * from test;
    
       ID_TEST     ID_CAT      DEBIT
    ---------- ---------- ----------
             1         22        456
             2         33        777
    
    SQL> select * From except_table;
    
    no rows selected
    
    SQL> select constraint_type, table_name, status, validated
      2  From user_Constraints
      3  where constraint_name = 'FK_TC';
    
    C TABLE_NAME      STATUS   VALIDATED
    - --------------- -------- -------------
    R TEST            ENABLED  VALIDATED        --> as everything went OK, constraint
                                                    is enabled and validated
      
    SQL>
    

    Exemplo #2 : chave pai da restrição de chave estrangeira ausente.

    Tabelas de amostra:

    SQL> drop table except_table;
    
    Table dropped.
    
    SQL> drop table test;
    
    Table dropped.
    
    SQL> drop table category;
    
    Table dropped.
    
    SQL> create table except_table
      2    (row_id     rowid,
      3     owner      varchar2(128),
      4     table_name varchar2(128),
      5     constraint varchar2(128)
      6    );
    
    Table created.
    

    Categoria agora está faltando ID_CAT = 33:

    SQL> create table category
      2    (id_cat number primary key);
    
    Table created.
    
    SQL> insert into category values (22);
    
    1 row created.
    
    SQL> create table test
      2    (id_test     number constraint pk_t primary key,
      3     id_cat      number constraint fk_tc references category,
      4     debit       number
      5    );
    
    Table created.
    
    SQL>
    

    O arquivo de controle não foi modificado - os dados de amostra ainda contêm ID_CAT = 33 linhas.

    load data
    infile *
    replace
    into table test
    reenable disabled_constraints exceptions except_table
    fields terminated by '|'
    trailing nullcols
    ( id_test,
      id_cat,
      debit
    )
    
    begindata
    1|22|456
    2|33|777
    

    Nada mudou na maneira como o sqlldr está sendo chamado; ambas as linhas (mesmo a inválida!) são carregadas:

    SQL>  $sqlldr scott/tiger@pdb1 control=test15.ctl log=test15.log direct=true
    
    SQL*Loader: Release 21.0.0.0.0 - Production on Sat Aug 19 21:44:00 2023
    Version 21.3.0.0.0
    
    Copyright (c) 1982, 2021, Oracle and/or its affiliates.  All rights reserved.
    
    Path used:      Direct
    
    Load completed - logical record count 2.
    
    Table TEST:
      2 Rows successfully loaded.
    
    Check the log file:
      test15.log
    for more information about the load.
    
    SQL>
    

    Log diz isso (leia com atenção !):

    Referential Integrity Constraint/Trigger Information:
    NULL, UNIQUE, and PRIMARY KEY constraints are unaffected.
    
    Constraint TEST.FK_TC was disabled and novalidated before the load.
    The following index(es) on table TEST were processed:
    index SCOTT.PK_T loaded successfully with 2 keys
    TEST.FK_TC was re-enabled.
    
    Table TEST has constraint exception table EXCEPT_TABLE.
    TEST.FK_TC was not re-validated due to ORACLE error.
    ORA-02298: cannot validate (SCOTT.FK_TC) - parent keys not found
    

    Resultado: ambas as linhas na testtabela (destino). except_Tableagora contém a linha que violou a restrição de chave estrangeira. O status da restrição é HABILITADO NÃO VALIDADO .

    SQL> select * from test;
    
       ID_TEST     ID_CAT      DEBIT
    ---------- ---------- ----------
             1         22        456
             2         33        777
    
    SQL> select * From except_table;
    
    ROW_ID             OWNER      TABLE_NAME      CONSTRAINT
    ------------------ ---------- --------------- ---------------
    AAAZRjAAMAAAASbAAB SCOTT      TEST            FK_TC
    
    SQL> select constraint_type, table_name, status, validated
      2  From user_Constraints
      3  where constraint_name = 'FK_TC';
    
    C TABLE_NAME      STATUS   VALIDATED
    - --------------- -------- -------------
    R TEST            ENABLED  NOT VALIDATED
    
    SQL>
    

    Se você tentar validar manualmente a restrição de chave estrangeira, não poderá fazer isso:

    SQL> alter table test modify constraint fk_tc enable validate;
    alter table test modify constraint fk_tc enable validate
                                       *
    ERROR at line 1:
    ORA-02298: cannot validate (SCOTT.FK_TC) - parent keys not found
    
    
    SQL>
    

    Primeiro remova a(s) linha(s) que violaram a restrição e, em seguida, valide-a:

    SQL> delete from test
      2  where not exists (select null from category
      3                    where category.id_cat = test.id_cat);
    
    1 row deleted.
    
    SQL> alter table test modify constraint fk_tc enable validate;
    
    Table altered.
    
    SQL>
    

    Portanto, sim - está tudo bem e funciona conforme o esperado.

    • 0

relate perguntas

  • importando um arquivo csv para o banco de dados oracle

  • Buscando registros de horas anteriores no Oracle

Sidebar

Stats

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

    destaque o código em HTML usando <font color="#xxx">

    • 2 respostas
  • Marko Smith

    Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}?

    • 1 respostas
  • Marko Smith

    Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)?

    • 2 respostas
  • Marko Smith

    Por que as compreensões de lista criam uma função internamente?

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 respostas
  • Marko Smith

    Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)?

    • 4 respostas
  • Marko Smith

    Por que o construtor de uma variável global não é chamado em uma biblioteca?

    • 1 respostas
  • Marko Smith

    Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto?

    • 1 respostas
  • Marko Smith

    Somente operações bit a bit para std::byte em C++ 17?

    • 1 respostas
  • Martin Hope
    fbrereto Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi Por que as compreensões de lista criam uma função internamente? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A formato fmt %H:%M:%S sem decimais 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python std::views::filter do C++20 não filtrando a visualização corretamente 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa Por que o construtor de uma variável global não é chamado em uma biblioteca? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev Por que os compiladores perdem a vetorização aqui? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan Somente operações bit a bit para std::byte em C++ 17? 2023-08-17 17:13:58 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

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