card 테이블의 '사용금액' 컬럼 총 합계를 구하는데
총 합계가 500만원이 넘으면 select '잘했어요;
넘지 못하면 select '분발하세요';
를 실행하고싶을 때 어떻게 코드를 짜야할까?
if나 case를 써도 되겠지만
그 문법들은 숫자나 문자 1개씩만 남겨주는 문법이기 때문에
조건에 따라 select같은 쿼리문은 남기지 못한다.
MySQL은 procedure 아니면 function안에서만 if를 사용할 수 있다.
if 조건식1 then
조건식1이 참이면 실행할 쿼리문;
elseif 조건식 2 then
조건식2가 참이면 실행할 쿼리문;
else
그게 아니면 실행할 쿼리문;
end if;
맨 위의 조건을 만족하려면 다음과 같이 코드를 짜면된다.
drop procedure if exists mart.test;
delimiter $$
create procedure mart.test()
begin
if(select sum(사용금액) from card) > 5000000 then
select '잘했어요';
else
select '분발하세요';
end if;
end
$$
delimiter ;
call mart.test();
함수 실행시 파라미터로 나이를 입력했을 때 20살 미만이면 '구매불가' 라는 문자를 내뱉고 아니면 '구매가능'을 뱉는 함수를 만들어보자.
drop function if exists mart.age_check;
delimiter $$
create function mart.age_check(나이 int)
returns varchar(100)
deterministic
begin
if(나이 > 19) then
return '성인';
else
return '미성년자';
end if;
end
$$
delimiter ;
select mart.age_check(20); // 성인