--
-- Host: localhost    Database: BUG_MARIA_DB
-- ------------------------------------------------------


--
-- Table structure for table `TABLE1`
--

CREATE TABLE `TABLE1` (
  `ID` int(11) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `TABLE1`
--


--
-- Table structure for table `TABLE2`
--

CREATE TABLE `TABLE2` (
  `ID` int(11) NOT NULL,
  `DATE` datetime DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `TABLE2`
--


--
-- Dumping routines for database 'BUG_MARIA_DB'
--
/*!50003 DROP PROCEDURE IF EXISTS `SP1` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `SP1`(IN _id INT(4))
BEGIN
  DECLARE done INT DEFAULT 0;
  DECLARE _myId INT;

  DECLARE _mySelect CURSOR FOR 
	SELECT DISTINCT TABLE1.ID
	FROM TABLE1  
		LEFT JOIN TABLE2 AS T2 ON 
			T2.ID = TABLE1.ID
			AND T2.DATE = (
				SELECT MAX(T3.DATE) FROM TABLE2 AS T3 WHERE T3.ID = T2.ID AND T3.DATE<=NOW()
			)
	WHERE TABLE1.ID = _id;

  DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;

  OPEN _mySelect;

  REPEAT
    FETCH _mySelect INTO _myId;

    
        
    

  UNTIL done END REPEAT;

  CLOSE _mySelect;
END ;;
DELIMITER ;


