Insert a select with more than one result

Asked

Viewed 469 times

1

need to execute the following command on an ORACLE DB: Elaborate a select that returns more than one result and the result of this select needs to be used to make an Insert in multiple lines.

Ex: my select returned 2 results: A and B, these results should be inserted in 2 lines:

A
B

How can I do that? Follows elaborate code:

DECLARE 
cursor insere is 
select campo_valor_tarefa.ds_valor from campo_valor_tarefa
inner join fluxo
on campo_valor_tarefa.cd_fluxo = fluxo.cd_fluxo
where campo_valor_tarefa.cd_tarefa = 2 and campo_valor_tarefa.cd_campo = 10 and fluxo.cd_processo = 180 and campo_valor_tarefa.cd_fluxo <344;

linha insere%rowtype;
BEGIN

OPEN insere;
loop
FETCH insere into linha;
exit when insere%notfound;

UPDATE campo_valor_tarefa set ds_valor = (
SELECT ds_valor FROM CAMPO_VALOR_TAREFA WHERE cd_campo = 10 AND cd_tarefa=2 AND cd_fluxo = 341
)
where cd_campo = 126 and cd_tarefa = 6 and cd_fluxo = 344;
end loop;
close insere;
end;

If I run select at the beginning of the code it returns 2 results and at the time of running Insert/update it inserts only 1 result on all lines.

1 answer

1

You need to do this using a loop, which for each "line" is made an Insert, see this example that makes a select and for each line makes a separate Insert:

create or replace procedure P_EXEMPLO  is
      Cursor CONSULTA IS
        select COLUNA1, COLUNA2 from TABELA order by 1, 2;
        LINHA CONSULTA %ROWTYPE;
      begin
        DBMS_OUTPUT.ENABLE(1000000);
        OPEN   CONSULTA;
        LOOP
        FETCH  CONSULTA  INTO   LINHA;
        EXIT   WHEN   CONSULTA%NOTFOUND;

          BEGIN 
              DBMS_OUTPUT.PUT_LINE('Incluindo novos registros');
              INSERT INTO TABLE2 VALUES(LINHA.COLUNA1, LINHA.COLUNA2);
          END;

        END LOOP; 
        COMMIT;
        CLOSE  CONSULTA;
      end P_EXEMPLO;
  • posted the code I made based on your example. It makes the select of 3 information, but adds only one on all lines.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.