DB/명령프롬프트 - mysql 예시

[MySQL] 프로시저 procedure 생성 예제

congs 2023. 3. 31. 16:20

product_name을 넣으면 구매한 customer 이름이 검색되는 프로시져

  • product_name을 in_product_name에 저장하고,
  • buy 테이블에서 in_product_name에 맞는 customer 칼럼 출력하는 프로시저 생성
  • in in_product_name varchar(45) 를 select_buy라는 프로시저의 속성에 저장
  • in은 생략이 가능
mysql> drop procedure if exists select_buy;

mysql> delimiter //

mysql> create procedure select_buy (
    -> in in_product_name varchar(45)
    -> )
    -> begin
    -> select customer from buy
    -> where product_name = in_product_name;
    -> end//
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;


mysql> call select_buy('폴라티셔츠');
+----------+
| customer |
+----------+
| 홍길동   |
| 다래     |
+----------+
2 rows in set (0.01 sec)
Query OK, 0 rows affected (0.01 sec)

 

소비자 이름을 넣으면  customer의 구매내역이 삭제되는 프로시저

  • 삭제가 되기전에 삭제될 데이터를 보여주는 구문
  • 삭제가 되는 구문
  • 삭제 후 남은 buy 테이블을 보여주는 구문
  • in_customer에 소비자 이름을 받음
mysql> drop procedure if exists delete_buy;

mysql> delimiter //

mysql> create procedure delete_buy (
    -> in in_customer varchar(45)
    -> )
    -> begin
    -> select * from buy where customer = in_customer;
    -> delete from buy where customer = in_customer;
    -> select * from buy;
    -> end//
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;

mysql> call delete_buy('졸려');
+-----+----------+-------------------+-------+--------+---------------------+
| num | customer | product_name      | price | amount | buy_date            |
+-----+----------+-------------------+-------+--------+---------------------+
|   8 | 졸려     | 순면라운드 반팔티 | 15900 |      5 | 2023-03-27 10:33:14 |
+-----+----------+-------------------+-------+--------+---------------------+
1 row in set (0.00 sec)

+-----+----------+----------------+-------+--------+---------------------+
| num | customer | product_name   | price | amount | buy_date            |
+-----+----------+----------------+-------+--------+---------------------+
|   1 | 홍길동   | 폴라티셔츠     | 15000 |      3 | 2023-03-24 17:22:02 |
|   2 | 홍길순   | 에어나시       |  9000 |      5 | 2023-03-24 17:22:02 |
|   3 | 이순신   | 양털 겨울 코트 | 50000 |      1 | 2023-03-24 17:22:02 |
|  15 | 홍길동   | 에어나시       |  9000 |      3 | 2023-03-30 15:24:03 |
+-----+----------+----------------+-------+--------+---------------------+
4 rows in set (0.01 sec)

Query OK, 0 rows affected (0.01 sec)

 

buy 테이블에 데이터를 추가하는 프로시저

  • insert로 customer, product_name, price, amout를 넣는 구문
  • update로 total = price + amout가 되는 구문
  • select로 전체 출력하는 구문