PL-SQL显式游标

时间:2013-03-16 17:59:59

标签: sql plsql oracle11g

我正在尝试为oracle编写一个PL?SQL语句,从表中选择所有唯一的Industries(Jobs Table)并将其插入另一个名为dim_industry

的表中
DECLARE
cursor industries is select unique industry from job;
ind varchar2(20);

BEGIN
  open industries;
  for counter in 1..industries%ROWCOUNT
  LOOP
    FETCH industries into ind;
    insert into dim_industry (IndustryName) values(ind);
  END LOOP;
  close industries;
END;
/

select unique industry from job

选择10行,但是当我运行pl-sql时,它表示插入了1行。另外,当我做一个

select * from dim_industry

查询,该表仍为空。关于为什么会发生这种情况的任何想法?

4 个答案:

答案 0 :(得分:4)

所有以前的答案都是改进 - 而BULK COLLECTION是一个非常有用的工具。但是您通常不需要使用PL / SQL来复制数据。在您的情况下,尝试使用INSERT ... SELECT语句,如下所示: -

INSERT INTO dim_industry( IndustryName )
SELECT DISTINCT industry
FROM job

PL / SQL是最后的手段恕我直言。我甚至在直接的Oracle SQL中实现了约束求解!

答案 1 :(得分:1)

ENDLOOP应写为END LOOP
更新
为了达到你想要的效果,你可以这样做:

    DECLARE
    cursor industries is select unique industry from job;
    ind varchar2(20);

    BEGIN
      open industries;
      LOOP
        FETCH industries into ind;
        exit when industries %notfound;
        insert into dim_industry (IndustryName) values(ind);
      END LOOP;
      close industries;
      commit;
    END;
/

答案 2 :(得分:1)

跳过这一步:

DECLARE 
    TYPE T_IND IS TABLE of job.industry%TYPE;
    ind T_IND;
BEGIN
    SELECT UNIQUE industry BULK COLLECT INTO ind FROM job;
    FORALL i IN ind.FIRST..ind.LAST
        INSERT INTO dim_industry (IndustryName) VALUES (ind(i));
    -- don't forget to commit;
END;
/

答案 3 :(得分:-1)

嘿,我认为你在其他路线上做的很漫长!!!试试这个家伙

DECLARE
  CURSOR c1
  iS
    select unique industry from job;
BEGIN
  FOR i IN c1
  LOOP
    INSERT INTO dim_industry (IndustryName) VALUES
      (i.industry
      );
  END LOOP;
  commit;
END;
/

如果您对游标使用for loop,则无需提及open and close它已隐式打开和关闭。 注意:如果你想使用带有批量操作的光标更好的用户集合在表上更新或插入删除操作,它会比这快得多。

这是做同样事情的第二种方式;

DECLARE
temp HR.departments.department_name%type;
  CURSOR c1
  iS
    SELECT DISTINCT d.department_name FROM hr.departments d;
BEGIN
  open c1;
  LOOP
  fetch c1  into temp;
    INSERT INTO thiyagu.temp_dep VALUES
      (temp
      );
      dbms_output.put_line(temp);
      exit when c1%notfound;
  END LOOP;
  close c1;
  commit;
END;
/

这是第三种有效的方式;

DECLARE

type test_type is  table of job.industry%type;

col test_type;

BEGIN
  select unique industry bulk collect into col from job;
  forall i in col.first..col.last insert into dim_industry values(col(i));
  dbms_output.put_line(sql%rowcount);
  commit;

END;
/