MySQL

커서(Cursor).MySQL

john_ 2023. 2. 10. 14:02
728x90

2023.02.10 - [MySQL] - 스토어드 함수(Stored Function)

 

스토어드 함수(Stored Function)

2023.02.10 - [MySQL] - 스토어드 프로시저(Stored Procedure).MySQL 스토어드 프로시저(Stored Procedure).MySQL 2023.02.08 - [MySQL] - 스토어드 프로시저(Procedure)를 이용한 프로그래밍.MySQL 스토어드 프로시저(Procedure)

less-go.tistory.com

 

이전 글에서 이어집니다.

 


커서의 개요

커서(Cursor)

  • 스토어드 프로시저 내부에 사용
  • 일반 프로그래밍 언어의 파일 처리와 방법이 비슷함
    • 행의 집합을 다루기 편리한 기능 제공
  • 테이블에서 여러 개의 행을 쿼리한 후, 쿼리의 결과인 행 집합을 한 행씩 처리하기 위한 방식입니다.

 

 


-- CURSOR 커서 사용
-- 고객의 평균 키를 구하는 스토어드 프로시저

use sqldb;

drop procedure if exists cursorProc;

delimiter $$
create procedure cursorproc()
begin
	declare userheight int;		-- 고객의 키
	declare cnt int default 0;	-- 고객의 수
    declare totalheight	int default 0;	-- 고객의 키 합계
    
    declare endofRow boolean default false;		-- 행의 끝인지 확인
    
    -- 커서선언
    declare userCursor cursor for
		select height from usertbl;
        
	declare continue handler		-- 행의 끝이면 endofRow 변수에 true를 대입
		for not found set endofRow = true;
	
    open userCursor;	-- 커서열기
    
    cursor_loop : LOOP
		FETCH userCursor INTO userHeight;		-- 고객 키를 하나씩 대입
		
        if endOfRow then
			leave cursor_loop;
		end if;
        
        set cnt = cnt + 1;						-- 고객 수를 누적
        set totalHeight = totalHeight + userHeight;
	end loop cursor_loop;
    
    select concat('고객의 키 평균 ==> ', (totalheight/cnt));
    
    close usercursor;
end $$
delimiter ;

call cursorproc();

 

728x90

'MySQL' 카테고리의 다른 글

전체 텍스트 검색.MySQL  (0) 2023.02.10
트리거(Trigger).MySQL  (0) 2023.02.10
스토어드 함수(Stored Function)  (0) 2023.02.10
스토어드 프로시저(Stored Procedure).MySQL  (0) 2023.02.10
인덱스 생성/ 변경 / 삭제.MySQL  (0) 2023.02.09