MySQL模拟Oracle的Sequence两种方法

来源:互联网 发布:互联网 大数据 生活 编辑:程序博客网 时间:2024/05/22 13:38

<!-- /* Font Definitions */ @font-face{font-family:宋体;panose-1:2 1 6 0 3 1 1 1 1 1;mso-font-alt:SimSun;mso-font-charset:134;mso-generic-font-family:auto;mso-font-pitch:variable;mso-font-signature:3 135135232 16 0 262145 0;}@font-face{font-family:"/@宋体";panose-1:2 1 6 0 3 1 1 1 1 1;mso-font-charset:134;mso-generic-font-family:auto;mso-font-pitch:variable;mso-font-signature:3 135135232 16 0 262145 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal{mso-style-parent:"";margin:0in;margin-bottom:.0001pt;mso-pagination:widow-orphan;font-size:12.0pt;font-family:"Times New Roman";mso-fareast-font-family:宋体;}@page Section1{size:8.5in 11.0in;margin:1.0in 1.25in 1.0in 1.25in;mso-header-margin:.5in;mso-footer-margin:.5in;mso-paper-source:0;}div.Section1{page:Section1;} /* List Definitions */ @list l0{mso-list-id:54815324;mso-list-type:hybrid;mso-list-template-ids:1437342586 67698705 67698713 67698715 67698703 67698713 67698715 67698703 67698713 67698715;}@list l0:level1{mso-level-text:"%1/)";mso-level-tab-stop:.5in;mso-level-number-position:left;text-indent:-.25in;}ol{margin-bottom:0in;}ul{margin-bottom:0in;}-->

Oracle 中可以创建Sequence,下面创建一个Sequence

 

CREATE SEQUENCE mysequence START WITH 1 INCREMENT BY 10

 

SEQUENCE的下一个值可以用mysequence.nextval获得,比如

 

SELECT mysequence.nextval fromdual.

或者

Insert into table( id, … ) values(mysequence.nextval, …)

 

MySQL不支持Sequence, 可以用stored procedurefunction模拟Oracle Sequence

 

1)      stored procedure方法

 

创建数据库表:

 

create table mysequence

(

      Idbigint not null auto_increment;

);

 

创建存储过程(使用动态SQL):

 

DELIMITER $$

 

drop PROCEDURE if exists nextval$$

 

CREATE PROCEDURE nextval( seq_namevarchar(64) )

BEGIN

     

 

      SET@sql= concat( 'insert into ', seq_name, ' values(NULL)');

      PREPAREs1 FROM @sql;

      executes1;

 

      SET@sql = concat ( 'DELETE FROM ', seq_name);

      PREPAREs2 FROM @sql;

      executes2;

      selectLAST_INSERT_ID();

END

$$

DELIMITER ;

 

调用存储过程获得mysequence的下一个值:

 

Call { nextval(‘mysequence’) }

 

将获得的值插入表中:

 

Insert into mytable( id,…) values(generated_id, …)

 

2)      function方法

 

同样创建数据库表:

 

create table mysequence

(

      Idbigint not null auto_increment;

);

 

创建一个函数:

 

DELIMITER$$

Drop function if exists `mysequence.nextval`$$

create function ` mysequence.nextval`()

RETURNS bigint

NOT DETERMINISTIC

READS SQL DATA

BEGIN

      insertmysequence values( NULL );

      deletefrom mysequence;

      returnLAST_INSERT_ID();

END

$$

DELIMITER ;

 

mysequence的下一个值插入表中:

 

Insert into mytable( id, … ) values( `mysequence.nextval`(),…);

 

第二种方法比较接近OracleSequence使用方法

原创粉丝点击