下面是MySQL的一个生成单号的实例。
单号生成规则是这样的,传递一个表名,然后根据表名查询出 表中的第一个列为id取出最大值然后判断最大值是否包含今天的日期,如果不包含则按照当前的日期YYYYMMDD日期生成比如格式为:
20140401001,否则,就在最大日期上进行加1.
然后返回单号。
?
具体代码如下:
??
#创建存储过程; DELIMITER $$ CREATE PROCEDURE genBillsNoPROC(IN tableName VARCHAR(30),OUT billsNoResult VARCHAR(100)) BEGIN DECLARE sql_1 VARCHAR(1000); DECLARE sql_2 VARCHAR(1000); DECLARE sql_3 VARCHAR(1000); DECLARE sql_4 VARCHAR(1000); DECLARE sql_5 VARCHAR(1000); SET sql_1 = CONCAT("SELECT COLUMN_NAME into @colName FROM information_schema.COLUMNS WHERE table_name='",tableName,"' limit 0,1"); #执行sql_1SQL语句; SET @frist_sql=sql_1; PREPARE stmt1 FROM @frist_sql; EXECUTE stmt1; SET sql_2 = CONCAT("select max(",@colName,"),instr(max(",@colName,"),DATE_FORMAT(NOW(),'%Y%m%d')) into @tableMaxValue,@sqlResult from ",tableName); #执行sql_2SQL语句; SET @second_sql=sql_2; PREPARE stmt2 FROM @second_sql; EXECUTE stmt2; SET sql_3 = CONCAT("SELECT t.bills_role_prefix into @billsPreFix FROM t_bills_role_setting t WHERE t.bills_table_name ='",tableName,"'"); #执行sql_3SQL语句; SET @three_sql=sql_3; PREPARE stmt3 FROM @three_sql; EXECUTE stmt3; #打印变量的值; SELECT @sqlResult; IF @sqlResult > 0 THEN #根据最大的单号如:SP20140101001 单号前缀SP ,最大单号长度-单号前缀长度 = 数字部分 ->转成数字 +1生成下一个单号 SET sql_4 = CONCAT("select CONVERT(right('",@tableMaxValue,"',length('",@tableMaxValue,"') - length('",@billsPreFix,"')),SIGNED)+1 into @billsNo from dual"); #执行sql_4SQL语句; SET @four_sql=sql_4; PREPARE stmt4 FROM @four_sql; EXECUTE stmt4; ELSE SET sql_5 = CONCAT("SELECT concat(DATE_FORMAT(NOW(),'%Y%m%d'),'001') into @billsNo from dual"); #执行sql_5SQL语句; SET @five_sql=sql_5; PREPARE stmt5 FROM @five_sql; EXECUTE stmt5; END IF; #设置返回结果(单号前缀+数字部分如:20140410001); SET billsNoResult := CONCAT(@billsPreFix,@billsNo); END$$
?
?
##执行存储过程 CALL genBillsNoProc('t_common_system',@data_t); SELECT @data_t maxValue;
?
返回结果:
SJZD20140410011