新接触oracle,有些问题不是很清楚在ms sql中 可以create table (id int primary key identity(1,1))实现这个字段的自增,insert的时候,就可以不用管这个字段了而且也不让赋值; oracle中实现似乎是用create sequence可是这个东西create完了 怎么知道是针对哪个表,哪个字段的?我做了一个这样的测试:
create sequence sq_acc_id
start with 1
increment by 1
nomaxvalue
nocycle;
create table system.account(
acc_id integer primary key,
acc_firstName varchar2(10) not null,
acc_lastName varchar2(10) not null,
acc_emailAddress varchar2(100) not null
);insert into account(acc_id,acc_firstname,acc_lastname,acc_emailaddress)
values(sq_acc_id.nextval,'san','zhang','[email protected]');select * from account;create table system.test(
id integer primary key
);insert into test(id)values(sq_acc_id.nextval);select * from test;发现test表中也自增了。如果这个自增不是针对某个表某个字段的,还有何意义?请高手指教下,oracle中该如何实现想ms sql中的自增?
create sequence sq_acc_id
start with 1
increment by 1
nomaxvalue
nocycle;
create table system.account(
acc_id integer primary key,
acc_firstName varchar2(10) not null,
acc_lastName varchar2(10) not null,
acc_emailAddress varchar2(100) not null
);insert into account(acc_id,acc_firstname,acc_lastname,acc_emailaddress)
values(sq_acc_id.nextval,'san','zhang','[email protected]');select * from account;create table system.test(
id integer primary key
);insert into test(id)values(sq_acc_id.nextval);select * from test;发现test表中也自增了。如果这个自增不是针对某个表某个字段的,还有何意义?请高手指教下,oracle中该如何实现想ms sql中的自增?
序列你已经建好了,再建个触发器就可以了。
也可以和触发器结合让其自增
create sequence sq_acc_id
start with 1
increment by 1
nomaxvalue
nocycle;
Create or Replace Trigger 触发器名
Before Insert On system.account
For Each Row
Begin
Select sq_acc_id.Nextval Into :New.acc_id From DUAL;
End;
同样一个sequence也可以同时被多个表的列使用。在数据库结构设计时,通常可以sequence和column的命名来标记出它们的联系。
我把这个加上了,但是似乎这个序列还是公用的,test的值紧跟account,在运行account还是紧跟test而不是account自己,而且对account表是以2为步长增加了
ORACLE SEQUENCE 介绍
http://blog.csdn.net/tianlesoftware/archive/2009/10/30/4745039.aspx
------------------------------------------------------------------------------
Blog: http://blog.csdn.net/tianlesoftware
网上资源: http://tianlesoftware.download.csdn.net
相关视频:http://blog.csdn.net/tianlesoftware/archive/2009/11/27/4886500.aspx
Q Q 群:62697716
使用触发器自增
sequence.nextval都会在当前值的基础上再计算一下,针对你的sequence就是每次都会加1.
(1)create table t_client (
id number(8) primary key,
pid number(4) not null,
name varchar2(30) not null,
client_id varchar2(10),
client_level char(3),
bank_acct_no varchar2(30),
contact_tel varchar2(30),
address varchar2(30),
zip_code varchar2(10),
is_leaf char(1) default 'y' check (is_leaf in('y','n')),
is_client char(1) default 'n' check (is_client in('y','n')
)); (2)假设关键字段为id,建一个序列,代码为:
create sequence seq_pk_t_client_id --这里的名称以seq_pk_打头,表示用于PK,以区别于其他非自增,不是约定俗成,只是我的习惯
minvalue 1
maxvalue 99999999 --这里的长度与表定义中的长度一致
start with 1
increment by 1
nocache
order;
(3)建触发器代码为:
CREATE OR REPLACE TRIGGER trg_t_client_id
BEFORE INSERT ON t_client
FOR EACH ROW
BEGIN
SELECT seq_pk_t_client_id.nextval INTO :new.id FROM dual;
END;
/
如果另一个字段需要自增,则重复(2),并在(3)中增加对应的select into语句。