11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 32 • STORED ROUTINESwww.it-ebooks.infoExecuting get_inventory will return:+-------------+| @inv |+-------------+| 45 |+-------------+Creating and Using Multistatement Stored RoutinesSingle-statement stored routines are quite useful, but stored routines’ real power lies in their ability toencapsulate and execute several statements. In fact, an entire language is at your disposal, enabling youto perform rather complex tasks such as conditional evaluation and iteration. For instance, supposeyour company’s revenues are driven by a sales staff. To coax the staff into meeting its lofty goals,bonuses are given out at the end of the year, with the size of the bonus proportional to the revenuesattributed to the employee. The company handles its payroll internally, using a custom Java program tocalculate and print the bonus checks at the conclusion of each year; however, a web-based interface isprovided to the sales staff so that it can monitor its progress (and bonus size). Because both applicationsrequire the ability to calculate the bonus amount, this task seems like an ideal candidate for a storedfunction. The syntax for creating this stored function looks like this:DELIMITER //CREATE FUNCTION calculate_bonus(emp_id CHAR(8)) RETURNS DECIMAL(10,2)COMMENT 'Calculate employee bonus'BEGINDECLARE total DECIMAL(10,2);DECLARE bonus DECIMAL(10,2);SELECT SUM(revenue) INTO total FROM sales WHERE employee_id = emp_id;SET bonus = total * .05;RETURN bonus;END;//DELIMITER ;The calculate_bonus function would then be called like this:mysql>SELECT calculate_bonus("35558ZHU");This function returns something similar to this:+-----------------------------+| calculate_bonus("35558ZHU") |+-----------------------------+| 295.02 |+-----------------------------+634

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!