mysql 实现id自增序列_【IT专家】mysql 如何设置自动增长序列 sequence(一)

本文由我司收集整编,推荐下载,如有疑问,请与我司联系

mysql

如何设置自动增长序列

sequence(

)

2016/03/29 0

背景:由于项目需要,必须用

mysql

设置主键自增长,而且想用

字符串的。经过上网查找并且实验,终于做出了一套方案。现在就共享给大家!

解决思路:由于

mysql

不带

sequence

,因此要手写的,创建一张储存

sequence

(tb_sequence)

,然后手动插入一条数据

,最后自定义一个函数来处理要增长的

值。

一起做吧:

1

、创建表

tb_sequence

,用来存放

sequence

值:

[sql]view

plaincopyprint?createtabletb_sequence(namevarchar(50)notnull,current_valueintnotnull,_i

ncrementintnotnulldefault1,primarykey(name));2

、手动插入数据:

[sql]view

plaincopyprint?insertintotb_sequencevalues(‘userid’,100,2);3

、定义函数

_nextval

[sql]view

plaincopyprint?DELIMITER//createfunction_nextval(nvarchar(50))returnsintegerbegindec

lare_curint;set_cur=(selectcurrent_valuefromtb_sequencewherename=n);updatetb_sequenc

esetcurrent_value=_cur+_incrementwherename=n;return_cur;end;//

说明:

delimiter

//

----

定义语句结束符。其他的代码

自己看吧。

4

、恢复默认的语句结束符:(可以省略但是结束符必须用

//

,为了方便还是设

置回来。

)

[sql]view plaincopyprint?DELIMITER;5

、检验结果

多次执行以下语句:

[sql]view plaincopyprint?select_nextval(‘userid’);

结果显示:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值