Can we use Select statement inside a loop in a Mysql Stored Procedure?
why is the code wrong
create procedure AbsentReportproc (INOUT fromdate DATET
Try this:
DELIMITER $$
DROP PROCEDURE IF EXISTS `AbsentReportproc`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `AbsentReportproc`(IN _fromdate DATETIME, IN _todate DATETIME)
BEGIN
CREATE TEMPORARY TABLE daterange (dte DATE);
SET @counter := -1;
WHILE (@counter < DATEDIFF(DATE(_todate), DATE(_fromdate))) DO
INSERT daterange VALUES (DATE_ADD(_fromdate, INTERVAL @counter:=@counter + 1 DAY));
END WHILE;
SELECT tp.cardno, tp.EMPCODE, tp.DEPARTMENT, GROUP_CONCAT(d.dte) Absentddate, COUNT(tp.cardno) Totalnoofabsentdates
FROM test_prefixmaster tp JOIN daterange d
LEFT JOIN test_prefixtransactions tpt ON tp.cardno = tpt.CARDNO AND DATE(S_DateTime) = d.dte
WHERE tpt.CARDNO IS NULL
GROUP BY tp.cardno;
DROP TABLE daterange;
END$$
DELIMITER ;
You didn't need a loop for this. You can do so:
SELECT
p.CARDNO,
COUNT(CARDNO) AS countdate
FROM test_prefixmaster p
INNER JOIN test_prefixtransactions t ON p.CARDNO = t.CARDNO
WHERE Date(t.S_DateTime) BETWEEN fromdate
AND todate
GROUP BY p.CARDNO;