繁体   English   中英

PL-SQL显式游标

[英]PL-SQL explicit cursors

我正在尝试为oracle编写PL?SQL语句,该语句从一个表(作业表)中选择所有唯一的行业并将其插入另一个名为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

查询时,该表保持为空。 有什么想法为什么会发生这种情况?

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

INSERT INTO dim_industry( IndustryName )
SELECT DISTINCT industry
FROM job

PL / SQL是IMHO的不得已的手段。 我什至已经在直接的Oracle SQL中实现了约束解决!

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;
/

跳过该步骤:

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;
/

嘿,我认为您在其他路线上所做的时间很长!

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;
/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM