]
Tags:
如何在MySQL&Oracle下创建自动递增字段
在MySQL下创建自动递增字段:
bitsCN_net中国网管博客
create table article //先创建一个表。
www.bitsCN.net网管博客等你来搏
(
id int primary key auto_increment, //设置该字段为自动递增字段。
title varchar()
);
bitsCN_net中国网管博客
insert into article values (null,'a'); //向数据库中插入数据。
www.bitsCN.net网管博客等你来搏
select * from article; 结果如下:
Id www.bitsCN.net网管博客等你来搏
Title
a
insert into article values (null,’b’);
insert into article values (null,'c');
insert into article (title) values ('d'); bitsCN_com关注网管是我们的使命
select * from article; 结果如下:
feedom.net国内最早的网管网站
Id bitsCN_com关注网管是我们的使命
Title feedom.net国内最早的网管网站
bitsCN_com
a
feedom.net国内最早的网管网站
bitsCN_com关注网管是我们的使命
b
bitsCN_com关注网管是我们的使命
c
d bitsCN_net中国网管博客
但是oracle没有这样的功能,但是通过触发器(trigger)和序列(sequence)可以实现。
bitsCN_com
假设关键字段为id,建一个序列,代码为:
create sequence seq_test_ids
minvalue
maxvalue
start with
increment by
nocache
bitsCN_com
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,上面的代码就可以实现自动递增的功能了。 bitsCN_com关注网管是我们的使命
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。