mySql通过函数生成日期+自增序列

set global log_bin_trust_function_creators=TRUE;

drop table if exists sequence;
create table sequence
(
    seq_name      VARCHAR(50) NOT NULL,           -- 序列名称
    current_year int default 0, -- 当前年
    init_val BIGINT NOT NULL,
    current_val   BIGINT         NOT NULL,           -- 当前值
    increment_val INT         NOT NULL DEFAULT 1, -- 步长(跨度)
    PRIMARY KEY (seq_name)
);

drop function currval;
DELIMITER ;;
create function currval(v_seq_name VARCHAR(50))
    returns varchar(64)
begin
    update sequence set current_year = YEAR(NOW()), current_val=init_val
    where seq_name = v_seq_name and current_year != YEAR(NOW());
    select CONCAT(current_year, current_val) into @value  from sequence where seq_name = v_seq_name;
    return @value ;
end;;

drop function nextval;
DELIMITER ;;
create function nextval (v_seq_name VARCHAR(50))
    returns bigint
begin
    update sequence set current_val = current_val + increment_val  where seq_name = v_seq_name;
    return currval(v_seq_name);
end;;

-- current_year一定要有初始值,year()与null不能直接做!=
INSERT INTO sequence VALUES ('generatorNumber', 0,1000000, 1000000, 1);

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值