본문 바로가기

ORACLE SQL

[Oracle] SQL문 - TYPE과 FOR문 활용 예시

728x90

1. aa_type이라는 타입을 만듭니다.

2. employees.first_name%type를 써서 원래 employees의 first_name의 타입을 그대로 가져옵니다.

3. index by binary_integer를 붙여 딕셔너리 형식으로 숫자를 넣고 값을 입력할수 있도록 만듭니다.

4. for 문을 활용해서 employees 테이블의 fist_name를 하나씩 읽어오고 이를 bb에 담아서 for문을 돌립니다.

5. idx 는 1씩 추가하도록 만들어 aa(숫자)의 숫자를 하나씩 늘리고 담아온 bb의 first_name을 aa(idx에 담습니다.)

6. for cc를 활용해서 값을 읽어옵니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
DECLARE
    type aa_type is table of employees.first_name%type index by binary_integer;
    aa aa_type;
    idx binary_integer := 0;
BEGIN
    FOR bb IN (select first_name from employees) LOOP
        idx := idx+1;
        aa(idx) := bb.first_name;
    END LOOP;
    
    FOR cc IN 1..idx LOOP
        DBMS_OUTPUT.PUT_LINE(RPAD(aa(cc),12));
    END LOOP;
END;
/
cs

 

아래는 type을 하나더 넣어서 만들어보았습니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
DECLARE
    type aa_type is table of employees.first_name%type index by binary_integer;
    aa aa_type;
    
    type ff_type is table of employees.salary%type index by binary_integer;
    ff ff_type;
    idx binary_integer := 0;
BEGIN
    FOR bb IN (select first_name,salary from employees) LOOP
        idx := idx+1;
        aa(idx) := bb.first_name;
        ff(idx) := bb.salary;
    END LOOP;
    
    FOR cc IN 1..idx LOOP
        DBMS_OUTPUT.PUT_LINE(RPAD(aa(cc),12)||' '||LPAD(ff(cc),12));
    END LOOP;
END;
/
cs