mysql 如何設置自動增長序列 sequence(一)


背景:由於項目需要,必須用mysql設置主鍵自增長,而且想用字符串的。經過上網查找並且實驗,終於做出了一套方案。現在就共享給大家!


解決思路:由於mysql不帶sequence,所以要手寫的,創建一張儲存sequence的表(tb_sequence),然后手動插入一條數據 ,最后自定義一個函數來處理要增長的值。

 

一起做吧:

1、創建表tb_sequence,用來存放sequence值:

 

[sql]  view plain  copy
 
 print?
  1. create table tb_sequence(name varchar(50) not null,current_value int not null,_increment int not null default 1, primary key(name));   


2、手動插入數據:

 

 

[sql]  view plain  copy
 
 print?
  1. insert into tb_sequence values('userid',100,2);  


3、定義函數 _nextval:

 

 

[sql]  view plain  copy
 
 print?
  1. DELIMITER //  
  2. create function _nextval(n varchar(50)) returns integer   
  3. begin  
  4. declare _cur int;  
  5. set _cur=(select current_value from tb_sequence where name= n);  
  6. update tb_sequence  
  7.  set current_value = _cur + _increment  
  8.  where name=n ;  
  9. return _cur;  
  10. end;  
  11. //  


說明:delimiter //   ---->定義語句結束符。其他的代碼 自己看吧。

 

4、恢復默認的語句結束符:(可以省略但是結束符必須用// ,為了方便還是設置回來。)

 

[sql]  view plain  copy
 
 print?
  1. DELIMITER ;  


5、檢驗結果 

 

多次執行以下語句:

 

[sql]  view plain  copy
 
 print?
  1. select _nextval('userid');  


結果顯示:

 

 

[sql]  view plain  copy
 
 print?
  1. mysql> select _nextval('userid');  
  2. +--------------------+  
  3. | _nextval('userid') |  
  4. +--------------------+  
  5. |                102 |  
  6. +--------------------+  
  7. 1 row in set (0.00 sec)  
  8.   
  9. mysql> select _nextval('userid');  
  10. +--------------------+  
  11. | _nextval('userid') |  
  12. +--------------------+  
  13. |                104 |  
  14. +--------------------+  
  15. 1 row in set (0.00 sec)  
  16.   
  17. mysql> select _nextval('userid');  
  18. +--------------------+  
  19. | _nextval('userid') |  
  20. +--------------------+  
  21. |                106 |  
  22. +--------------------+  
  23. 1 row in set (0.00 sec)  


6、實驗結束。

 

 


免責聲明!

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



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