在oracle中使用序列(Sequence)来处理主键字段,现在想要在Mysql中也实现类似的效果。
1 drop table if exists sequence; 2 create table sequence ( 3 seq_name VARCHAR(50) NOT NULL, -- 序列名称 4 current_val INT NOT NULL, -- 当前值 5 increment_val INT NOT NULL DEFAULT 1, -- 步长(跨度) 6 PRIMARY KEY (seq_name));
1 INSERT INTO sequence VALUES ('seq_test', '0', '1');
1 create function currval(v_seq_name VARCHAR(50)) 2 returns integer(11) 3 begin 4 declare value integer; 5 set value = 0; 6 select current_val into value from sequence where seq_name = v_seq_name; 7 return value; 8 end;
1 select currval('seq_test');
1 create function nextval (v_seq_name VARCHAR(50)) returns integer(11) 2 begin 3 update sequence set current_val = current_val + increment_val where seq_name = v_seq_name; 4 return currval(v_seq_name); 5 end;
1 select nextval('seq_test');