0

I have to fetch bulk record and insert into table using loop I have little confusion how to fetch and insert record using loop. Below I have shared what I have done so far .

declare
    stud_Id varchar;
begin            
    stud_Id := select student_id from student_backup where is_active_flg ='Y';

    for i in 1 ..stud_Id.count
    loop
        insert into users(student_id,password,status) values(stud_Id(i),'password','status')
        where not exists (select student_id from users where student_id=stud_Id(i))
    end loop;

    commit;
end;
/
2

2 Answers 2

2

You can use the following :

declare
  stud_Id student_backup.student_id%type;
begin
     select nvl(max(student_id),0) into stud_Id 
       from student_backup 
      where is_active_flg ='Y';

   if stud_Id >0 then
    for i in 1 ..stud_Id
    loop
       insert into users(student_id,password,status) 
       select b.student_id,'password','status'
         from student_backup b 
         left join users u on b.student_id = u.student_id
        where is_active_flg ='Y'
          and b.student_id = i;
    end loop;
   end if; 
    commit;
end;
/

Demo

P.S. If I understood you want to perform, you don't need to use for loop(including if statement) and the select statement in the beginning, but directly apply the insert statement by removing the part and b.student_id = i. So, convert your block to the one as below :

declare
  stud_Id student_backup.student_id%type;
begin

       insert into users(student_id,password,status) 
       select b.student_id,'password','status'
         from student_backup b 
         left join users u on b.student_id = u.student_id
        where is_active_flg ='Y' ;
    commit;
end;
/
Sign up to request clarification or add additional context in comments.

9 Comments

dear can you please elaborate why you use max(student_id) instead of count(student_id).
hi @AbdulRaheem. I thought you need to scan all the possible values of student_id. If some not exists between 1 and max(student_id), then it's already skipped, and iterate to the max value.
@AbdulRaheem assume you have 50 students with ID through 1 to 100. Whenever 1..count(student_id) is used for the loop, the ID with 51 to 100 will not be considered.
@BarbarosÖzhan you won't hit a no_data_found exception with a max query.
Hi @AbdulRaheem. I don't use skype. My e-mail is [email protected]
|
0

Abdul,

I think you are searching for the following:

BEGIN

INSERT INTO USERS 
SELECT STUDENT_ID, PASSWORD , STATUS
FROM student_backup
WHERE STUDENT_ID NOT IN (SELECT STUDENT_ID FROM USERS)
AND is_active_flg = 'Y';

END;
/

Hope, this will be useful.

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.