DROP FUNCTION COMM_AMOUNT;
CREATE FUNCTION COMM_AMOUNT(SALARY DEC(9,2))
  RETURNS DEC(9,2)
  LANGUAGE SQL READS SQL DATA
  BEGIN ATOMIC
    DECLARE REMAINDER DEC(9,2) DEFAULT 0.0;--
    DECLARE COMM_PAID DEC(9,2) DEFAULT 0.0;--
    DECLARE COMM_INCR INT      DEFAULT 1;--
    DECLARE MAX_COMM  DEC(9,2) DEFAULT 0.0;--

    IF (SALARY <= 0) THEN
       SIGNAL SQLSTATE '75000'
         SET MESSAGE_TEXT = 'Bad Salary';--
    END IF;--

    SET REMAINDER = SALARY;--

L1: WHILE REMAINDER > 0.0 DO
      SET COMM_PAID = COMM_PAID + (COMM_INCR * 500.00);--
      SET REMAINDER = REMAINDER-(COMM_INCR * 5000.00);--
      SET COMM_INCR = COMM_INCR + 1;--
    END WHILE L1;--

    SET MAX_COMM =
       (SELECT SUM(SALARY)/100.00 FROM EMPLOYEE);--
    IF (COMM_PAID > MAX_COMM) THEN
       SET COMM_PAID = MAX_COMM;--
    END IF;--
    RETURN COMM_PAID;--
END;
