簡體   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