mysql怎么写一个序列 c语言烟花表白代码

mysql如何创建一个序列序列只有db2
oracle有,mysql没有序列的,不过你可以给你所所创建的表的主键设置为自增 。
例如
create
table
A
(
id
int(20)
auto_increment
)
不过设置为自增的键必须是数值类型的 。
mysql 如何创建序列?比如说你创建了一个表userinfos
create table userinfos(
userid int primary key,
username varchar(20)
);
//给userinfos添加序列
update userinfos set userid = last_insert_id(userid+1);
//然后查询序列
select last_insert_id();
或者也可以这样
create table userinfos(
userid int primary key not null auto_increment,
username varchar(20)
);
MySQL实现类似Oracle序列的方案MySQL实现类似Oracle的序列
Oracle一般使用序列(Sequence)来处理主键字段 , 而MySQL则提供了自增长(increment)来实现类似的目的;
但在实际使用过程中发现,MySQL的自增长有诸多的弊端:不能控制步长、开始索引、是否循环等;若需要迁移数据库,则对于主键这块,也是个头大的问题 。
本文记录了一个模拟Oracle序列的方案,重点是想法 , 代码其次 。
Oracle序列的使用 , 无非是使用.nextval和.currval伪列,基本想法是:
1、MySQL中新建表,用于存储序列名称和值;
2、创建函数 , 用于获取序列表中的值;
具体如下:
表结构为:
drop
table
if
exists
sequence;
create
table
sequence
(
seq_name
VARCHAR(50)
NOT
NULL,
--
序列名称
current_val
INT
NOT
【mysql怎么写一个序列 c语言烟花表白代码】NULL,
--当前值
increment_val
INT
NOT
NULL
DEFAULT
1,
--步长(跨度)
PRIMARY
KEY
(seq_name)
);
实现currval的模拟方案
create
function
currval(v_seq_name
VARCHAR(50))
returns
integer
begin
declare
value
integer;
set
value
=
0;
select
current_value
into
value
from
sequence
where
seq_name
=
v_seq_name;
return
value;
end;
函数使用为:select
currval('MovieSeq');
实现nextval的模拟方案
create
function
nextval
(v_seq_name
VARCHAR(50))
return
integer
begin
update
sequence
set
current_val
=
current_val
+
increment_val
where
seq_name
=
v_seq_name;
return
currval(v_seq_name);
end;
函数使用为:select
nextval('MovieSeq');
增加设置值的函数
create
function
setval(v_seq_name
VARCHAR(50),
v_new_val
INTEGER)
returns
integer
begin
update
sequence
set
current_val
=
v_new_val
where
seq_name
=
v_seq_name;
return
currval(seq_name);
同理,可以增加对步长操作的函数,在此不再叙述 。
注意语法,数据库字段要对应上
use
bvboms;
DELIMITER
$$
create
function
setval(v_seq_name
VARCHAR(50),
v_new_val
INTEGER)
returns
integer
begin
update
sequence
set
current_val
=
v_new_val
where
seq_name
=
v_seq_name;
return
currval(seq_name);
end
$$
DELIMITER
$$
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持 。如果你想了解更多相关内容请查看下面相关链接

推荐阅读