11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

www.it-ebooks.infoCHAPTER 35 • PRACTICAL DATABASE QUERIESOpening a CursorAlthough the cursor’s query is defined in the DECLARE statement, the query isn’t actually executed untilthe cursor has been opened. You accomplish this with the OPEN statement:OPEN cursor_nameFor example, to open the calc_bonus cursor created earlier in this section, execute the following:OPEN calc_bonus;Using a CursorUsing the information pointed to by the cursor is accomplished with the FETCH statement. Its prototypefollows:FETCH cursor_name INTO varname1 [, varname2...]For example, the following stored procedure (stored procedures were introduced in Chapter 32),calculate_bonus(), fetches the id, salary, and commission columns pointed to by the cursor, performsthe necessary comparisons, and finally inserts the appropriate bonus:DELIMITER //CREATE PROCEDURE calculate_bonus()BEGINDECLARE emp_id INT;DECLARE sal DECIMAL(8,2);DECLARE comm DECIMAL(3,2);DECLARE done INT;DECLARE calc_bonus CURSOR FOR SELECT id, salary, commission FROM employees;DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;OPEN calc_bonus;BEGIN_calc: LOOPFETCH calc_bonus INTO emp_id, sal, comm;IF done THENLEAVE begin_calc;END IF;IF sal > 60000.00 THENIF comm > 0.05 THENUPDATE employees SET bonus = sal * comm WHERE id=emp_id;689

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

Saved successfully!

Ooh no, something went wrong!