简体   繁体   中英

for loop in oracle PLSQL

I want the value i to increment by 1 for every insert in the table employee_dep

i := 1
For lh in
 (SELECT DISTINCT z.emp_id
           FROM employee z)
LOOP
 INSERT INTO employee_dep
        (emp_id, emp_lfd, dep_name, dept_no)
        SELECT w.emp_id, i, w.dep_name, w.dep_no)
        FROM
          central_dep w
        where w.emp_id= lh.emp_id;
         i := i+1;
end loop;

But if there are two rows with same emp_id then i is same for both the rows. I want i to be incremented by 1 in the next row. (i to be incremented by 1 for every new insert in the table)

for eg. i wanted the columns to be

emp_id emp_lfd
1111     1
1111     2
1111     3
1122     1
1122     2
1122     3
1122     4

But what i am currently getting is

emp_id emp_lfd
1111     3
1111     3
1111     3
1122     4
1122     4    
1122     4
1122     4

Don't you just want an insert ... select statement with row_number() ?

insert into employee_dep (emp_id, emp_lfd, dep_name, dept_no)
select emp_id, row_number() over(order by emp_id), dep_name, dep_no
from central_dep

Or, if you are practicing PL/SQL, that would be a nested loop, eg

DECLARE
   i  NUMBER;
BEGIN
   i := 1;

   FOR lh IN (SELECT DISTINCT z.emp_id
                FROM employee z)
   LOOP
      FOR cur_r IN (SELECT w.emp_id, w.dep_name, w.dep_no
                      FROM central_dep w
                     WHERE w.emp_id = lh.emp_id)
      LOOP
         INSERT INTO employee_dep (emp_id,
                                   emp_lfd,
                                   dep_name,
                                   dept_no)
              VALUES (cur_r.emp_id,
                      i,
                      cur_r.dep_name,
                      cur_r.dep_no);

         i := i + 1;
      END LOOP;
   END LOOP;
END;

Seems that you just need ROW_NUMBER() analytic function with PARTITION BY emp_id within your INSERT statement such as

INSERT INTO employee_dep(emp_id, emp_lfd, dep_name, dept_no)
SELECT emp_id, ROW_NUMBER() OVER (PARTITION BY emp_id ORDER BY 0), dep_name, dep_no
  FROM central_dep

I've tried to regenerate your case within the Demo

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.

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