存储过程创建下个月每天表的小例子

delimiter $$
CREATE PROCEDURE sp_create_table()
BEGIN
	    --下个月是什么年份
		DECLARE next_year int;
        --下个月是几月份
		DECLARE next_month int;
        --下个月 最后一天是几号
		DECLARE next_day int;


        --拼接下个月字符串,1-9月添加0,比如07月
		DECLARE next_month_str VARCHAR(2);
        --拼接日期字符串,1-9号添加0,比如09号
		DECLARE next_day_str VARCHAR(2);

        --表名
		DECLARE table_name_str VARCHAR(20);
        --控制循环,1号至下个月最后一天
		DECLARE t_index int DEFAULT 1;


		SET next_year = YEAR(DATE_ADD(now(),INTERVAL 1 month));
		SET next_month = MONTH(DATE_ADD(NOW(),INTERVAL 1 MONTH));
		SET next_day = DAYOFMONTH(LAST_DAY(DATE_ADD(NOW(),INTERVAL 1 MONTH)));

		IF (next_month<10)
				THEN SET next_month_str = CONCAT('0',next_month);
		ELSE
				SET next_month_str = CONCAT('',next_month);
		END IF;

		WHILE t_index<=next_day DO

				IF (t_index<10)
						THEN SET next_day_str = CONCAT('0',t_index);
				ELSE
						SET next_day_str = CONCAT('',t_index);
				END IF;

				SET table_name_str =         
                    CONCAT('comp_',next_year,'_',next_month_str,'_',next_day_str);


				SET @create_table_sql = CONCAT('create table ',table_name_str,' (`grade` 
       int(11) NULL,`losal`int(11) NULL) COLLATE=\'utf8_general_ci\' ENGINE=InnoDB');


				PREPARE create_table_stmt FROM @create_table_sql;
				EXECUTE create_table_stmt;
				DEALLOCATE PREPARE create_table_stmt;

				SET t_index = t_index+1;
			
		END WHILE;

END $$

call sp_create_table();

 

你可能感兴趣的:(SQL,存储过程小例子)