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 / 79052159
Accepted
Ray
Ray
Asked: 2024-10-04 05:03:40 +0800 CST2024-10-04 05:03:40 +0800 CST 2024-10-04 05:03:40 +0800 CST

Instrução Oracle PL SQL Insert - ORA-01007: variável não está na lista de seleção

  • 772

Tenho um script que copia registros que atendem a uma condição específica para uma tabela temporária. A tabela original é então truncada e os registros são copiados de volta.

A instrução usada para criar a tabela temporária é;

create table ARCHIVE_TMP as select * from ORIGINAL_TABLE where TIMESTAMP_UPDATED < '2017-10-04'

E a declaração para copiar os registros novamente é;

insert /*+ APPEND */ into ORIGINAL_TABLE select * from ARCHIVE_TMP

Quando a segunda linha é executada no script, ela gera a exceção ORA-01007: variable not in select list, mas se eu executar manualmente a segunda instrução, ela funciona como esperado.

Verifiquei se o usuário tem privilégios CREATE e INSERT, pois houve um problema anteriormente em que os privilégios foram atribuídos a uma função em vez do usuário.

Também tentei especificar os nomes das colunas na selectinstrução em vez de usar select *, mas isso não ajudou.

A seguir está o roteiro completo;

create or replace procedure TRUNCATE_EXPIRED_ARCHIVE_DATA
(
    p_retention_period      in number   := 84, 
)
as
begin
    declare
        cursor table_cursor is
            select      owner, table_name, column_name, data_type
            from        all_tab_columns
            where       table_name like '%!_A' escape '!'
                        and column_name like 'TIMESTAMP!_%' escape '!'
            group by    owner, table_name, column_name, data_type           
            order by    table_name, column_name;
        RetentionDt     date := null;
        ExpiredCount    number := 0;
        InsertedCount   number := 0;
        TableExists     number := 0;
        ExpiredSql      varchar2(500);
        SelectSql       varchar2(800);
        SqlStmt         varchar2(1300);
    begin
        RetentionDt := add_months(sysdate, p_retention_period * -1);
        for table_rec in table_cursor loop
            begin
                -- Check if there are any expired records...
                SelectSql := 'select count(*) from ' || table_rec.owner || '.' || table_rec.table_name;
                ExpiredSql := ' where ' || table_rec.column_name || ' < ''' || RetentionDt || '''';
                SqlStmt := SelectSql || ExpiredSql;
                execute immediate SqlStmt into ExpiredCount;
                if (ExpiredCount > 0) then
                    -- Drop the temporary table if it already exists...
                    SelectSql := 'select count(*) from tab where tname = ''ARCHIVE_TMP''';
                    execute immediate SelectSql into TableExists;
                    if (TableExists > 0) then
                        SelectSql := 'drop table REODT_PROD.ARCHIVE_TMP';
                        execute immediate SelectSql;
                    end if;
                    -- Transfer the records to be retained to the temporary table...
                    SelectSql := 'create table REODT_PROD.ARCHIVE_TMP as select * from ' || table_rec.owner || '.' || table_rec.table_name || ' where ' || table_rec.column_name || ' >= ''' || to_char(RetentionDt, 'YYYY-MM-DD') || '''';
                    execute immediate SelectSql;
                    InsertedCount := sql%rowcount;
                    commit;
                    if (InsertedCount > 0) then
                        SelectSql := 'truncate table ' || table_rec.owner || '.' || table_rec.table_name;
                        dbms_output.put_line('Truncate Table    : ' || SelectSql);
                        execute immediate SelectSql;
                        SelectSql := 'insert /*+ APPEND */ into ' || table_rec.owner || '.' || table_rec.table_name || ' select * from REODT_PROD.ARCHIVE_TMP';
                        execute immediate SelectSql into InsertedCount;
                        commit;
                    end if;
                end if;
            end;
        end loop;
    end;
end;
/
oracle
  • 1 1 respostas
  • 26 Views

1 respostas

  • Voted
  1. Best Answer
    MT0
    2024-10-04T06:29:06+08:002024-10-04T06:29:06+08:00
    SelectSql := 'insert /*+ APPEND */ into ' || table_rec.owner || '.' || table_rec.table_name || ' select * from REODT_PROD.ARCHIVE_TMP';
    execute immediate SelectSql into InsertedCount;
    

    É um INSERT(e não um SELECT), então você não quer ter uma INTOcláusula.

    Você pode simplificar o procedimento para:

    create or replace procedure TRUNCATE_EXPIRED_ARCHIVE_DATA
    (
        p_retention_period      in number   := 84
    )
    as
      TABLE_NOT_FOUND EXCEPTION;
      RetentionDt     date := add_months(TRUNC(sysdate), -p_retention_period);
      ExpiredCount    number := 0;
      InsertedCount   number := 0;
    
      PRAGMA EXCEPTION_INIT(TABLE_NOT_FOUND, -942);
    begin
      for table_rec in (
        select      owner, table_name, column_name, data_type
        from        all_tab_columns
        where       table_name like '%!_A' escape '!'
        and         column_name like 'TIMESTAMP!_%' escape '!'
        order by    table_name, column_name
      ) loop
        -- Check if there are any expired records...
        execute immediate
             'select count(*)'
          || ' from "' || table_rec.owner || '"."' || table_rec.table_name || '"'
          || ' where "' || table_rec.column_name || '" < :1'
          INTO ExpiredCount
          USING RetentionDt;
        IF ExpiredCount = 0 THEN
          DBMS_OUTPUT.PUT_LINE(
            '"' || table_rec.owner || '"."' || table_rec.table_name || '" Not found'
          );
          CONTINUE;
        END IF;
        BEGIN
          execute immediate 'drop table REODT_PROD.ARCHIVE_TMP';
        EXCEPTION
          WHEN TABLE_NOT_FOUND THEN
            NULL;
        END;
        execute immediate
             'create table REODT_PROD.ARCHIVE_TMP as'
          || ' select * from "' || table_rec.owner || '"."' || table_rec.table_name || '"'
          || ' where "' || table_rec.column_name || '"'
          || ' >= TIMESTAMP ''' || TO_CHAR(RetentionDt, 'YYYY-MM-DD HH24:MI:SS') || '''';
    
        InsertedCount := sql%rowcount;
        commit;
    
        if InsertedCount > 0 then
          execute immediate 'truncate table "' || table_rec.owner || '"."' || table_rec.table_name || '"';
          execute immediate
               'insert /*+ APPEND */ into "' || table_rec.owner || '"."' || table_rec.table_name || '"'
            || ' select * from REODT_PROD.ARCHIVE_TMP';
          commit;
        end if;
      end loop;
    end;
    /
    

    violino

    • 1

relate perguntas

  • Oracle - Execuções Restantes

  • Servidor ODBC Informix: Erro ao extrair o nome do mês da data

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

  • 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

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle?

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Quando devo usar um std::inplace_vector em vez de um std::vector?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Marko Smith

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

    • 1 respostas
  • Martin Hope
    Aleksandr Dubinsky Por que a correspondência de padrões com o switch no InetAddress falha com 'não cobre todos os valores de entrada possíveis'? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer Quando devo usar um std::inplace_vector em vez de um std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB Por que o GCC gera código que executa condicionalmente uma implementação SIMD? 2024-02-17 06:17:14 +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