I simply need to return a list of all days within a month. I\'m not accessing a specific table. So I need a sql select statement if given the month of February, return the
I agree with the comments, that something like this shouldn't be done in the database, but technically its possible. If you give the start and end date, adding additional numbers to the subquery if necessary:
SELECT '2011-02-01' + INTERVAL a + b DAY dte
FROM
(SELECT 0 a UNION SELECT 1 a UNION SELECT 2 UNION SELECT 3
UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7
UNION SELECT 8 UNION SELECT 9 ) d,
(SELECT 0 b UNION SELECT 10 UNION SELECT 20
UNION SELECT 30 UNION SELECT 40) m
WHERE '2011-02-01' + INTERVAL a + b DAY < '2011-03-01'
ORDER BY a + b
Results:
"2011-02-01"
"2011-02-02"
"2011-02-03"
....
"2011-02-28"
I have slightly augmented to give the all preceeding dates for the last month:
SELECT (SELECT Date(NOW() - INTERVAL 1 MONTH)) + INTERVAL a + b DAY dte FROM (SELECT 0 a UNION SELECT 1 a UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 ) d, (SELECT 0 b UNION SELECT 10 UNION SELECT 20 UNION SELECT 30 UNION SELECT 40) m WHERE (SELECT Date(NOW() - INTERVAL 1 MONTH)) + INTERVAL a + b DAY < (select date(now())) ORDER BY a + b;
-- This may be overkill, but you can make a procedure like this:
use dbname;
DELIMITER $$
DROP PROCEDURE IF EXISTS `days_of_month` $$
CREATE PROCEDURE `days_of_month`(iDate DATETIME) DETERMINISTIC
BEGIN
DECLARE last_day,mm,yy,dd INT DEFAULT 0;
SET dd = 1;
SET mm = month(iDate);
SET yy = year(iDate);
set iDate = case when iDate is null then now() else iDate end;
SET last_day = date_format(LAST_DAY(iDate),'%d');
DROP TABLE IF EXISTS `days_of_month_tblTemp`;
CREATE TEMPORARY TABLE days_of_month_tblTemp(tmpDate DATE);
label1: LOOP
insert into days_of_month_tblTemp(tmpDate) values (concat(yy,'-',mm,'-',dd));
SET dd = dd + 1;
IF dd < (last_day+1) THEN ITERATE label1; END IF;
LEAVE label1;
END LOOP label1;
SELECT * from days_of_month_tblTemp;
END $$
DELIMITER ;
-- run it like this: CALL days_of_month('2012-02-22');