mysql 自動生成編號函數


根據需求,保存表數據時需要自動生成一個編號,格式如:AA-2020-03-31-0001  (AA-yyyy-MM-dd-序號)。數據庫用的mysql,所以創建一個mysql函數。

1、建表:

create table sys_sequence_number(
sequenceType varchar(30) not null,
val int not null,
len int not null
);

 

2、建函數

DELIMITER $$
DROP FUNCTION IF EXISTS getSequenceNo $$
create function getSequenceNo(pSequenceType varchar(30),pLen int) returns varchar(60)
begin
declare strZero varchar(20) default '00000000000000000000';
declare strSequenceNo varchar(60) default '';
declare iVal int default 0;
declare iLen int default 0;
declare c int default 0;
select count(1) into c from sys_sequence_number where sequenceType=pSequenceType;
if(c<1)
then
insert into sys_sequence_number(sequenceType,val,len)
values(pSequenceType,0,pLen);
end if;

update sys_sequence_number set val=val+1 where sequenceType=pSequenceType;
select val,len into iVal,iLen from sys_sequence_number where sequenceType=pSequenceType;

set strSequenceNo=concat(substr(strZero,1,iLen-length(iVal)),convert(iVal,char(10)));
return concat(concat(pSequenceType,'-'),strSequenceNo);

end $$
DELIMITER ;

 

3、在mysql上執行測試: select  getSequenceNo(concat('AA-',date_format(now(), '%Y-%m-%d')),4)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM