MySql : List of Previous Months

We are going  to see here, listing out the number of previous months from the current month.
Below function will retrieve the list of months depends on the input give by the user. The code is,

DELIMITER $$
DROP FUNCTION IF EXISTS `DEMO_DB`.`month_list`$$

CREATE DEFINER=`root`@`localhost

` FUNCTION `month_list`(numMonths tinyint) RETURNS text CHARSET latin1
BEGIN
DECLARE l_counter int default 0;
declare retValue text;
SET retValue=”;
TestLoop: loop
 if l_counter >= numMonths then
     leave TestLoop;
  end if;
                 
              SET retValue= CONCAT(retValue,MONTHNAME(DATE_ADD(NOW(), INTERVAL -l_counter MONTH)),’,’);
  set l_counter = l_counter + 1;
 end loop TestLoop;
SET retValue = TRIM(TRAILING ‘,’ FROM retValue);
return retValue;
    END$$
DELIMITER ;
Input :
                  SELECT month_list(3);
 

 

Output:
             
March,February,January
 Run the function in your mysql(phpmyadmin) to store the function on any database after that just execute the function as seen above given input.
 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: