I am trying to write a PL?SQL statement for oracle that selects all unique Industries from a table (Jobs Table) and inserts it into another table called 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;
/
The
select unique industry from job
Selects 10 rows, but when I run the pl-sql, it says 1 row inserted. Also, when I do a
select * from dim_industry
query, the table remains empty. Any ideas as to why this would happen?
All the previous answers are improvements - and BULK COLLECTION is a very useful tool. But you generally don't need to use PL/SQL to copy data around. In your case, try just using an INSERT ... SELECT statement like so :-
INSERT INTO dim_industry( IndustryName )
SELECT DISTINCT industry
FROM job
PL/SQL is a last resort IMHO. I've even implemented constraint solving in straight Oracle SQL!
ENDLOOP
should be written as END LOOP
UPDATE
To achieve what you want, You can proceed like this:
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;
/
skip that step:
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;
/
hey i think your doing in other route which is quite lengthy!!!just try this dude
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;
/
if you use for loop
for cursor then no need mention open and close
it has implicitly open and close. note:if you want to update or insert of delete operation on table using cursor better user collections with bulk operation it's much faster than this.
this is second way to do the same;
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;
/
this is third and efficient way;
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;
/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.