본문 바로가기

Database/PLSQL

010 - [Oracle PL/SQL] For Loop

<샘플코드에서 사용한 데이터는 HR 스키마이고, 오라클 설치시 생성할 수 있는 기본 스키마 입니다>

 

 

# basic for loop

begin
    for i in 1..3
    loop
    dbms_output.put_line('welcome '||i);
    end loop;

end;
------------------------
begin
    for i in 1..1
    loop
    dbms_output.put_line('welcome '||i);
    end loop;

end;
--------------------
begin
    for i in 3..5
    
    loop
    dbms_output.put_line('welcome '||i);
    end loop;

end;
--------------------


welcome 1
welcome 2
welcome 3

welcome 1

welcome 3
welcome 4
welcome 5

 

 

 

# 감소하는 for 문

begin
    for i in reverse 1..3 
    loop
    dbms_output.put_line('welcome '||i);
    end loop;

end;
-------------------------
welcome 3
welcome 2
welcome 1

 

 

 

#oracle will round 4.5, so it will be 5

begin
    for i in 1..9/2
    loop
    dbms_output.put_line('welcome '||i);
    end loop;

end;
------------------------------------------------
welcome 1
welcome 2
welcome 3
welcome 4
welcome 5

 

 

 

declare
v_name varchar2(200);
begin
    for i in 100..102
    loop
        select first_name||' '||last_name
        into v_name
        from
        employees
        where employee_id=i;
        
        dbms_output.put_line(i||':'||v_name);
        
    end loop;
end;
------------------------------------------------
100:Steven King
101:Neena Kochhar
102:Lex De Haan