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

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

WBOY
WBOYOriginal
2016-06-07 15:14:211192browse

欢迎进入Oracle社区论坛,与200万技术人员互动交流 >>进入 如何在 MySQLOracle 下创建自动递增字段 在 MySQL 下创建自动递增字段: create table article // 先创建一个表。 ( id int primary key auto_increment, // 设置该字段为自动递增字段。 title varc

欢迎进入Oracle社区论坛,与200万技术人员互动交流 >>进入

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

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

Statement:
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