Home > Database > Mysql Tutorial > 如何在MySQL&Oracle下创建自动递增字段_MySQL

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-01 13:59:08
Original
951 people have browsed it

 
         如何在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;
        
        
         建解发器代码为:
         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,上面的代码就可以实现自动递增的功能了。

 

Related labels:
how
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template