1

我正在尝试为 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

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

4

4 回答 4

4

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

INSERT INTO dim_industry( IndustryName )
SELECT DISTINCT industry
FROM job

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

于 2013-03-17T17:19:23.927 回答
1

ENDLOOP应该写成END LOOP
UPDATE
来实现你想要的,你可以这样进行:

    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;
/
于 2013-03-16T18:02:27.543 回答
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;
/
于 2013-03-16T18:53:07.913 回答
-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;
/
于 2013-03-17T05:53:19.057 回答