Select statement inside a loop in a Mysql Stored Procedure

前端 未结 2 1206
盖世英雄少女心
盖世英雄少女心 2021-01-16 04:08

Can we use Select statement inside a loop in a Mysql Stored Procedure?

why is the code wrong

create procedure AbsentReportproc (INOUT fromdate DATET         


        
相关标签:
2条回答
  • 2021-01-16 04:31

    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 ;
    
    0 讨论(0)
  • 2021-01-16 04:40

    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;
    
    0 讨论(0)
提交回复
热议问题