如何在MySQL&Oracle下创建自动递增字段


 
         如何在MySQL&Oracle下创建自动递增字段
         在MySQL下创建自动递增字段:
         create table article   //先创建一个表。
         (       
          id int primary key auto_increment,  //设置该字段为自动递增字段。
          title varchar(255)
         );
         insert into article values (null,'a');     //向数据库中插入数据。
         select * from article;   结果如下:
         Id Title 
1 a

         insert into article values (null,’b’);
         insert into article values (null,'c');
         insert into article  (title)  values ('d');
         select * from article;   结果如下:
         Id Title 
1 a
2 b
3  c
4 d

         但是oracle没有这样的功能,但是通过触发器(trigger)和序列(sequence)可以实现。
         假设关键字段为id,建一个序列,代码为:
         create sequence seq_test_ids
         minvalue 1
         maxvalue 99999999
         start with 1
         increment by 1
         nocache
         order;
         <!--[if !supportLineBreakNewLine]-->
         <!--[endif]-->
         建解发器代码为:
         create or replace trigger tri_test_id
         before insert on test_table 
         for each row
         declare
         nextid number;
begin
  IF :new.id IS NULLor :new.id=0 THEN
    select seq_test_id.nextval
    into nextid
    from sys.dual;
    :new.id:=nextid;
  end if;
end tri_test_id;
         OK,上面的代码就可以实现自动递增的功能了。

 

本文作者:
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3