How can you in a procedure function in mysql check if the cursor returns anything?
Is it possible to avoid doing the IF (SELECT COUNT(*) FROM stock ... and instead check up on the _cur variable somehow?
procedure function
DELIMITER $$
DROP FUNCTION IF EXISTS `stock_first_available_id` $$
CREATE DEFINER=`dynaccount`@`localhost` FUNCTION `stock_first_available_id`(_running_total_limit INT, _product_id INT, _group_id INT) RETURNS INT
BEGIN
DECLARE _running_count INT default 0;
DECLARE _id INT;
DECLARE _current_id INT;
DECLARE _sum_count INT;
DECLARE _cur CURSOR FOR SELECT id, count FROM stock WHERE group_id=_group_id && type=2 && product_id=_product_id ORDER BY time DESC, id DESC;
IF (SELECT COUNT(*) FROM stock WHERE group_id=_group_id && type=2 && product_id=_product_id) = 0 THEN
RETURN 0;
END IF;
OPEN _cur;
read_loop: LOOP
FETCH _cur INTO _id, _sum_count;
SET _running_count = _running_count + _sum_count;
SET _current_id = _id;
IF _running_count > _running_total_limit THEN
LEAVE read_loop;
END IF;
END LOOP read_loop;
CLOSE _cur;
RETURN _current_id;
END $$
DELIMITER ;
Add a continue handler to your cursor. See exanples from MySQL documentation.
http://dev.mysql.com/doc/refman/5.0/en/cursors.html