存储过程 练习二利用存储过程循环创建表

-- 知识点 预处理 prepare 语句 from 后使用局部变量会报错

PREPARE stmt_name FROM preparable_stmt

EXECUTE stmt_name [ USING @var_name [ ,@var_name ] .. ]

{ DEALLOCATE | DROP } PREPARE stmt_name

-- 知识点 时间的处理

(现在的时间:2021-12-09 14:54:00)

-- EXTRACT(unit FROM date):截取时间的指定位置值

-- DATE_ADD(date,INTERVAL expr unit):日期运算

 

-- LAST_DAY(date):获取日期的最后一天

-- YEAR(date):获取日期中的年

 -- MONTH(date):获取日期中的月

 -- DAYOFMONTH(date):获取日期中的日

创建下个月的每天对应的表 comp_2020_04_01、comp_2020_04_02、...

(模拟)需求描述:

我们需要用某个表记录很多数据,比如记录某某用户的搜索、购买行为(注意,此处是假设用数据库保存),当每天记录较多时,如果把所有数据都记录到一张表中太庞大,需要分表,我们的要求是,每天一张表,存当天的统计数据,就要求提前生成这些表--每月底创建下一个月每天的表。

delimiter // 
create procedure sp_create_table()
begin
    declare next_year int;
    declare next_month int;
    declare next_month_str char(2);
    declare next_month_day int;
    declare next_month_day_str char(2);

    -- 处理每天的表名
    declare table_name_str char(10);
    declare t_index int default 1;
    
    -- 获取下个月的年份
    set next_year = year(data_add(now(),INTERVAL 1 month));
    -- 获取下个月的月份
    set next_month = month(data_add(now(),INTERVAL 1 month));
    -- 下个月最后一天是几号
    set next_month_day = dayofmonth(LAST_DAY(data_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_month_day do

        if(t_index < 10)
            then set next_month_day_str = concat('0',t_index ); 
        else
            set next_month_day_str = concat('',t_index ); 
        end if;

        set table_name_str = 
concat(next_year,'_', next_month_str ,'_', next_month_day_str );

        -- 拼接create sql 语句
        set @create_table_sql = concat(
                'create table comp_',
                table_name_str,
                '(`grade` INT(11) NULL,`losal` INT(11) NULL,`hisal` INT(11) NULL) COLLATE=\'utf8_general_ci\' ENGINE=InnoDB');
        -- from 后面不能使用局部变量
        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//

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值