Reputation: 41
im using mysql stored procedure, how can I make a loop that in every 1 hour the variable strathour will have 1 hour interval then return the ouptut of the query which is total. While the starthour is less than the date of november it will have interval of 1 hour and perform the query.
here's my code:
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `sp_asessiontime`(
out `total` int
)
BEGIN
declare `starthour`, `endhour` datetime;
set `starthour` = '2012-09-20 01:59:00';
set `endhour` = '2012-09-20 02:00:00';
select count(terminalcount.terminalids) into total from (
select distinct ts.TerminalID `terminalids` from
tmptransactiondetails td
inner join transactionsummary ts
on td.TransactionSummaryID = ts.TransactionsSummaryID
where
td.ServiceID = 4
and
td.TransactionType in ('D','W')
and
(ts.DateStarted >= starthour and ts.DateStarted < endhour)
or
(ts.DateEnded >= starthour and ts.DateEnded < endhour)
or
(ts.DateStarted < starthour and starthour <= ts.DateEnded)
)as terminalcount;
-- loop for every 1 hour
while
starthour < '2012-11-01 01:59:00' do
select starthour + interval 1 hour;
select total as totalnumber;
end while;
END
Thank you so much guys.
Upvotes: 4
Views: 20241
Reputation: 17724
I am not sure I got your question correctly, but this is how you loop between dates
set currHour = '2012-09-20 01:59:00';
set endhour = '2012-09-21 02:00:00';
REPEAT
-- execute your queries for every hour
Set currHour = DATE_ADD(currHour,INTERVAL 1 HOUR);
UNTIL currHour > endhour END REPEAT;
if you must use the while loop:
WHILE currHour < endhour DO
-- execute your queries for every hour
Set currHour = DATE_ADD(currHour,INTERVAL 1 HOUR);
END WHILE;
Upvotes: 10