카테고리 없음

[오라클/SQL] Cursor(커서) 실행 및 예제

eun_zoey2 2022. 6. 13. 12:19
728x90
Cursor란?

    커서를 짧고 간략하게 설명 하면 "SQL문을 처리한 결과 집합을 가리키는 포인터이다.

DECLARE
PRODUCT_ID varchar2(100);
PRODUCT_NAME varchar2(100);
CURSOR EX_CUR
IS
SELECT PRODUCT_ID, PRODUCT_NAME FROM PRODUCTS;
BEGIN
OPEN EX_CUR;
DBMS_OUTPUT.PUT_LINE('제품코드 제품명'); 
LOOP
FETCH EX_CUR INTO PRODUCT_ID, PRODUCT_NAME; 
EXIT WHEN EX_CUR %NOTFOUND;
DBMS_OUTPUT.PUT_LINE(PRODUCT_ID ||' '|| PRODUCT_NAME);
END LOOP;
CLOSE EX_CUR;
END;
/

1. 테이블 생성 

create table customerss(id number(10), name varchar2(20), age number(10),
address varchar2(30), salary number(10));

insert into customerss values(1,'Lee',32, 'Seoul', 2000.00);
insert into customerss values(2,'Park',25, 'Busan', 1500.00);
insert into customerss values(3,'Kim',25, 'Incheon', 6500.00);
insert into customerss values(4,'Pyo',30, 'Suwon', 8200.00);
insert into customerss values(5,'Hong',22, 'Daegu', 4500.00);

2. 암시적 커서의 속성

SQL%FOUND 해당 SQL문에 의해 반환된 총 행수가 1개 이상일 경우TRUE (BOOLEAN)
SQL%NOTFOUND 해당 SQL문에 의해 반환된 총 행수가 없을 경우 TRUE (BOOLEAN)
SQL%ISOPEN 항상 FALSE, 암시적 커서가 열려 있는지의 여부 검색( PL/SQL은 실행 후 바로 묵시적 커서를 닫기 때문에
항상  false)
SQL%ROWCOUNT 해당 SQL문에 의해 반환된 총 행수, 가장 최근 수행된 SQL문에 의해 영향을 받은 행의 갯수(정수)
set serveroutput on;
DECLARE  
   total_rows number(2); 
BEGIN 
   UPDATE customerss  
   SET salary = salary + 500; 
   IF sql%notfound THEN 
      dbms_output.put_line('no customer selected'); 
   ELSIF sql%found THEN 
      total_rows := sql%rowcount;
      dbms_output.put_line( total_rows || ' customer selected '); 
   END IF;  
END; 
/

3. 명시적 커서

set serveroutput on;
DECLARE                          
   c_id customerss.id%type;      
   c_name customerss.name%type; 
   c_addr customerss.address%type; 
   CURSOR c_customerss is       
      SELECT id, name, address FROM customerss;  
BEGIN 
   OPEN c_customerss; 
   LOOP 
   FETCH c_customerss into c_id, c_name, c_addr; 
      EXIT WHEN c_customerss%notfound; 
      dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr); 
   END LOOP; 
   CLOSE c_customerss; 
END; 
/

암시적커서와 명시적커서 사용법