mysql 編號產生,mysql編號
1、序號產生的方法
DELIMITER $$CREATE DEFINER=`root`@`localhost` FUNCTION `get_workNo`() RETURNS varchar(45) CHARSET utf8BEGINDECLARE newWorkNo varCHAR (45) ;DECLARE currentDate varCHAR (15) ;-- 當前日期,有可能包含時分秒 DECLARE maxNo INT DEFAULT 0 ;DECLARE oldWorkNo VARCHAR (25) DEFAULT '' ;-- 離現在最近的滿足條件的訂單編號 SELECT SUBSTRING(DATE_FORMAT(NOW(), '%Y%m'),3,6) INTO currentDate ;SELECT IFNULL(workNo, '') INTO oldWorkNo FROM operation_work WHERE SUBSTRING(workNo, 3, 4) = currentDate ORDER BY id DESC LIMIT 1 ; -- 有多條時只顯示離現在最近的一條 IF oldWorkNo != '' THEN SET maxNo = CONVERT(SUBSTRING(oldWorkNo, -4), DECIMAL) ;-- SUBSTRING(oldOrderNo, -5):訂單編號如果不為‘‘截取訂單的最後5位 END IF ;SELECT CONCAT('TS', currentDate, LPAD((maxNo + 1), 4, '0')) INTO newWorkNo ;RETURN newWorkNo;END$$DELIMITER ;
2、插入資料時的觸發器
USE `it_system`;DELIMITER $$CREATE DEFINER=`root`@`localhost` TRIGGER `operation_work_BINS` BEFORE INSERT ON `operation_work` FOR EACH ROWbegin SET @workNo = get_workNo(); set NEW.workNo=@workNo;end