DB/명령프롬프트 - mysql

[MySQL] 프로시저 procedure (함수)

congs 2023. 3. 31. 11:52

프로시저  procedure 

: 쿼리의 집합

  • 일련의 쿼리를 마치 하나의 함수처럼 실행하기 위한 쿼리의 집합
  • 메서드와 동일한 역할
  • 어떠한 동작을 절차적 일괄처리 작업하는데 사용
  • 장점 
    • 처리시간의 단축 : 한번에 SQL 구문 처리가 가능
    • 유지 보수에 적합

 

프로시저 procedure 삭제

drop pricedure if exists 프로시저명 ;

 

프로시저 procedure 매개변수

  1. in 
    • 외부에서 가져와 내부에서만 사용하는 매개변수
    • 프로시저에 값을 전달, 프로시저 내부에서 값 수정 가능
    • in 매개변수는 복사본만을 사용
    • 가장 많이 사용
  2. out 
    • 내부에서 생성되어 외부로 리턴하는 매개변수
    • 프로시저의 값을 호출자에게 다시 전달 ( = 리턴)
    • 프로시저가 반환되는 경우, 새로운 값이 호출자에게 리턴
    • 초기값 = 프로시저 내부에서 null값을 가짐
  3. inout
    • in + out
    • 호출자에의해 하나의 변수가 초기화되고, 변경된 값을 호출자에게 리턴
    • 예) 점수를 받아 합계를 리턴

 

프로시저 procedure 생성

delimiter //

create procedure 프로시저명 ( 
in 매개변수,  
out 매개변수
...
)

begin
쿼리 실행문
end//

delimiter ;
delimiter //

mysql> create procedure insert_customer (
    -> in in_customer varchar(45),
    -> in in_product_name varchar(45),
    -> in in_price int,
    -> in in_amount int
    -> )
    -> begin
    -> insert into buy (customer, product_name, price, amount) values
    -> (in_customer, in_product_name, in_price, in_amount);
    -> update buy set total = in_price + in_amount where customer = in_customer;
    -> select * from buy;
    -> end//

delimiter ;

 

프로시저 procedure 호출 (사용)

call 프로시저명( ) ;

 

프로시저 procedure 확인

-- 전체 프로시저 확인
show prodedure status ;
-- 선택 데이터베이스의 프로시저 목록 확인
show prodedure status where db = '데이터베이스명' ;
-- 프로시저 하나만 확인
show create procedure 프로시저명 ;