使用Cursor变量在存储过程中插入循环

时间:2013-10-17 18:24:53

标签: oracle stored-procedures plsql cursor

我有一个存储过程,我需要从表中获取所有id并在其他表中插入带有这些id的新行,但我不太了解函数游标

PROCEDURE INSERTMDCGENERAL AS

 idCat NUMERIC;
 CURSOR cur IS
    SELECT ID_CAT_FILTROS_TALENTO into idCat FROM MDC_CAT_FILTROS_TALENTO;

  BEGIN 

    FOR v_reg IN cur LOOP
      INSERT INTO MDC_FILTROS_TALENTO(ID_FILTRO,ID_CAT_FILTROS_TALENTO)
               VALUES(SEC_MDC_FILTROS_TALENTO.NextVal,idCat);    
    END LOOP;

COMMIT;

END INSERTMDCGENERAL;

2 个答案:

答案 0 :(得分:2)

做一些比以下更复杂的事情几乎没有任何意义:

PROCEDURE INSERTMDCGENERAL AS
BEGIN 

      INSERT INTO MDC_FILTROS_TALENTO 
           (ID_FILTRO,ID_CAT_FILTROS_TALENTO)
      SELECT SEC_MDC_FILTROS_TALENTO.NextVal
             , ID_CAT_FILTROS_TALENTO 
      FROM MDC_CAT_FILTROS_TALENTO;

      COMMIT;

END INSERTMDCGENERAL;

这在大多数情况下都适用。只有当你处理数百万行时,你才需要修饰它。即使这样,你也不应该使用游标循环和逐行处理:这样效率要低得多。

答案 1 :(得分:1)

这可能是你期待的......

PROCEDURE INSERTMDCGENERAL AS
 idCat NUMERIC;
 CURSOR cur IS  SELECT ID_CAT_FILTROS_TALENTO FROM MDC_CAT_FILTROS_TALENTO;

  BEGIN 
  open cur;
  loop
    fetch cur into idCat;
    exit when cur%notfound;
      INSERT INTO MDC_FILTROS_TALENTO(ID_FILTRO,ID_CAT_FILTROS_TALENTO)
               VALUES(SEC_MDC_FILTROS_TALENTO.NextVal,idCat);    
  END LOOP;
  close cur;
 COMMIT;

 END INSERTMDCGENERAL;