2012-12-31 89 views
1

我們可以在Mysql存儲過程的循環中使用Select語句嗎?在Mysql存儲過程的循環中選擇語句

爲什麼是錯誤的代碼

create procedure AbsentReportproc (INOUT fromdate DATETIME, INOUT todate DATETIME) 
as 
begin 

DECLARE startdate DATE; 
DECLARE enddate DATE; 
DECLARE nofdays INT; 
DECLARE counter INT; 
DECLARE countdate DATE; 
startdate=fromdate; 
enddate=todate; 
countdate=fromdate; 

nofdays=DATEDIFF(DAY,startdate,endate); 
counter=1; 

while counter<=noofdays 
loop 

select CARDNO from test_prefixmaster 
where CARDNO not in ( select CARDNO from test_prefixtransactions where Date(S_DateTime)=countdate) 

set countdate=countdate+1; 
set counter=counter+1; 
end loop; 

end// 

回答

2

試試這個:

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:[email protected] + 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

我們可以在while循環中使用Select語句嗎? – String

+0

是的,但它會在無日期時間返回表格。意味着noofdays價值4比你的輸出contove 4表 –

+0

什麼是在你的程序中使用while循環的原因。解釋你想要用表結構,sample dat和output來做什麼。 –

0

你並不需要爲這個循環。你可以這樣做:

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;