data engineering

mysql procedure 선언문 예제

qkqhxla1 2017. 3. 28. 14:58

함수라고 생각하면 되는 프로시저. for문을 도는 프로시저 예제.



DELIMITER $$

DROP PROCEDURE IF EXISTS loop_test $$ -- loop_test라는 프로시저가 이미 있으면 지움.

CREATE PROCEDURE loop_test(var INT) -- 프로시저 정의문

BEGIN

    DECLARE nCnt INT DEFAULT 0;

    DECLARE nTot INT DEFAULT 0; 

    loop_xxxx:LOOP 

       IF (var <= nCnt) THEN

          LEAVE loop_xxxx; -- loop 탈출 조건 (탈출 조건을 사용하기 위해서는 루프의 이름이 지정되어야 함.) 

       END IF;  

       SET nCnt = nCnt + 1;

       SET nTot = nTot + nCnt; 

    END LOOP;

 

    SELECT CONCAT(CONCAT(CONCAT('1 부터 ', var), ' 까지의 합은 '), nTot) AS total; -- 결과 값 출력

 

END $$

DELIMITER ;


Call loop_test(10); 


프로그래밍을 어느정도 하면 대충 슥 보고 이해가는데 몇가지 이해가 안가는 사실이 있다. 첫줄의 DELIMITER $$ 이게 왜있을까..? 끝에도 있고. 이걸 지우면 제대로 실행이 안된다. 


이유는 한문장 한문장을 구분하는 구분자가 ;인데 이걸 잠시 $$로 바꿔줘서(DELIMITER $$구분의 역할.) 중간에 프로시저를 정의할때 ;가 나와도 한문장으로 인식하지 않고, 그냥 문자로 생각하게끔 해서 끝까지 정의한 후 끝에와서 DELIVITER ;로 다시 ;로 구분자를 바꿔준다는 것이었다.


http://alextsilverstein.com/programming-and-development/mysql/mysql-the-reason-for-using-the-delimiter-statement-in-mysql-routines-stored-procedures-functions-triggers/


해당 링크의 2번 내용만 가져왔다. 구분자에 관한 내용이다.


2) The next step is to change the default MySQL script parser’s delimiter from semicolon (;) to double-dollar sign ($$). The reason you do this is so that the semicolons after each statement in the body of the routine are not interpreted by the parser as meaning the end of the CREATE PROCEDURE statement. This is because the entire CREATE PROCEDURE block, from CREATE PROCEDURE to END is actually a single statement that must be executed by itself. Were it not for the delimiter change, the script would break, since there each statement inside BEGIN and END would execute individually. Note that you can use a variety of non-reserved characters to make your own custom delimiter.


굳이 이렇게 루프를 돌릴때 프로시저를 만들어서 돌리는 이유는 mysql 에디터에서 프로시저 없이 루프 돌리기가 불가능하기 때문이라고 한다.


http://stackoverflow.com/questions/14739940/can-i-run-a-loop-in-mysql-without-using-a-procedure-function

'data engineering' 카테고리의 다른 글

mapreduce(맵리듀스)란?  (0) 2017.05.20
docker 삽질.  (0) 2017.04.25
redis 기초.  (2) 2017.04.20
index (mongodb)  (0) 2017.04.20
docker getting started  (0) 2017.04.17