[pl/sql] 세금을 계산하는 함수를 만들어 보자(if, case, decode 및 세율 테이블 이용)

이상원·2023년 11월 16일

PL/SQL

목록 보기
1/5

문제

다음 조건을 만족하는 tax 함수를 만들어서 사용하는 예제를 만드세요.

  • salary가 10000 미만이면 0.013 세율 적용
  • salary가 20000 미만이면 0.015 세율 적용
  • salary가 20000 이상이면 0.02 세율 적용

해답 1. if문 사용

create or replace function tax1(
      p_salary number
    ) return number
    is
      v_tax number;
    begin
      if p_salary < 10000 then
        v_tax := p_salary * 0.013;
      elsif p_salary < 20000 then
        v_tax := p_salary * 0.015;
      else
        v_tax := p_salary * 0.02;
      end if;

      return v_tax;
    end;
    /

해답 2. case문 사용

create or replace function tax2(
      p_salary number
    ) return number
    is
      v_tax number;
    begin
      v_tax := case when p_salary < 10000 then p_salary * 0.013
                    when p_salary < 20000 then p_salary * 0.015
                    else                       p_salary * 0.02
               end;
      return v_tax;
    end;
    /

해답 3. decode문 사용

create or replace function tax3(
      p_salary number
    ) return number
    is
      v_tax number;
    begin
      select decode(trunc(p_salary/10000), 0, p_salary*0.013,
                                           1, p_salary*0.015,
                                              p_salary*0.02)
             into v_tax
      from dual;

      return v_tax;

    end;
    /

해답 4. 세율 테이블 만들기

  drop table t_tax_rate purge;

    create table t_tax_rate
    (id          number generated as identity,
     lowest_sal  number,
     highest_sal number,
     tax_rate    number);

    insert into t_tax_rate(lowest_sal, highest_sal,tax_rate) values (0,     10000, 0.013);
    insert into t_tax_rate(lowest_sal, highest_sal,tax_rate) values (10000, 20000, 0.015);
    insert into t_tax_rate(lowest_sal, highest_sal,tax_rate) values (20000, null,  0.02);

    commit;

    select * from t_tax_rate;

    create or replace function tax4(
      p_salary number
    ) return number
    is
      v_tax_rate t_tax_rate.tax_rate%type;
    begin
      select tax_rate
      into v_tax_rate
      from t_tax_rate
      where p_salary  >= lowest_sal
      and   p_salary  < nvl(highest_sal, 100000000);

      return p_salary * v_tax_rate;
    end;
    /

결과

  select salary,
         tax1(salary) as tax1,
         tax2(salary) as tax2,
         tax3(salary) as tax3,
         tax4(salary) as tax4
  from employees;

해설

해답 1,2,3은 각 조건에 맞도록 분기하는 조건문을 사용하여 풀이하였다.
물론 해당 문제에서 답은 맞지만 비지니스 로직이 바뀐다면 함수를 계속 수정해주어야 하는 단점이 있다.

--예를 들어 15000 이하의 급여를 받는 사람의 세율이 0.014로 바뀐다면 기존의 이 부분을
if p_salary < 10000 then
        v_tax := p_salary * 0.013;
-->
if p_salary < 15000 then
        v_tax := p_salary * 0.014;
-- 이렇게 바꾸어 주어야 한다.

따라서 해답 4처럼 세율을 정의하는 테이블을 만들고 소득마다의 범위와 세율을 정의하여 넣어놓으면 비지니스 로직이 바뀌어도 해당 테이블만 수정하면 기존의 함수를 계속 사용할 수 있다.

profile
Sang9riG9ru

0개의 댓글