自動定義序號:用來作"定單號"測試
總會有這樣的需求,只是可能你沒有遇到而已。我舉個例子:若訂單號的生成格式爲「日期+序號」rem
(先無論需求是否是很傻逼),就像這樣:2015052200001234,這個該如何處理呢?next
如果有序列號,就比較好解決了。從00000001開始,到99999999,而後重置爲一下序列,就OK啦。數據
-- 定義序列表生成
DROP TABLE IF EXISTS sequence;日期
CREATE TABLE sequence (
name VARCHAR(50) NOT NULL,
current_value INT NOT NULL,
increment INT NOT NULL DEFAULT 1,
PRIMARY KEY (name)
) ENGINE=InnoDB;
-- 獲取當前序列號
DROP FUNCTION IF EXISTS currval;
DELIMITER $
CREATE FUNCTION currval (seq_name VARCHAR(50))
RETURNS INTEGER
CONTAINS SQL
BEGIN
DECLARE value INTEGER;
SET value = 0;
SELECT current_value INTO value
FROM sequence
WHERE name = seq_name;
RETURN value;
END$
DELIMITER ;
-- 獲取下一個序列號
DROP FUNCTION IF EXISTS nextval;
DELIMITER $
CREATE FUNCTION nextval (seq_name VARCHAR(50))
RETURNS INTEGER
CONTAINS SQL
BEGIN
UPDATE sequence SET current_value = current_value + increment
WHERE name = seq_name;
RETURN currval(seq_name);
END$
DELIMITER ;
-- 重設序列號
DROP FUNCTION IF EXISTS setval;
DELIMITER $
CREATE FUNCTION setval (seq_name VARCHAR(50), value INTEGER)
RETURNS INTEGER
CONTAINS SQL
BEGIN
UPDATE sequence SET current_value = value
WHERE name = seq_name;
RETURN currval(seq_name);
END$
DELIMITER ;
-- 初始化數據
INSERT INTO sequence VALUES ('SAMPLE', 1, 1);
-- 測試
SELECT currval('SAMPLE');
SELECT nextval('SAMPLE');
SELECT nextval('SAMPLE');
SELECT setval('SAMPLE',150);
SELECT currval('SAMPLE');
SELECT nextval('SAMPLE');
SELECT nextval('SAMPLE');