oracle主鍵自增長
來源:互聯網
上載者:User
oracle主鍵自增長 1、比較土鱉的方式定義主鍵number類型,之後每次存資料時候,id為取得此表的max(id),之後+1,在存放進去 可以用時間作為主鍵,唯一。2、官方版 使用序列方式,增長主鍵。下面介紹使用過程。建立測試表 t [sql] SQL> create table t( 2 id number(10) primary key, 3 name varchar2(20) not null); www.2cto.com Table created 建立序列sequence t_id [sql] SQL> create sequence t_id 2 start with 2 --以2開始 3 increment by 2; --以2為自增長1、3、5、7... Sequence created 使用序列[sql] SQL> insert into t values(t_id.nextval,'人1'); 1 row inserted SQL> insert into t values(t_id.nextval,'人1'); 1 row inserted www.2cto.com SQL> insert into t values(t_id.nextval,'人1'); 1 row inserted SQL> insert into t values(t_id.nextval,'人1'); 1 row inserted 查詢表t [sql] SQL> select * from t; ID NAME ----------- -------------------- 2 人1 4 人1 6 人1 8 人1 刪除表資料刪除表 [sql] SQL> truncate table t; www.2cto.com Table truncated SQL> drop table t; Table dropped 恢複刪除表 [sql] flashback table t to before drop; 序列詳情介紹 [sql] --序列 /* *需求:在插入記錄時,主索引值,需要不重複而且唯一, *它的值靠人工產生不太靠普,所以我們需要一個能產生值的一個東西, *這個東西就是序列,序列是一個資料庫物件。產生序列的文法: */ create sequence [user.]sequence_name [start with n]1 [increment by n]/*以n=2為增長1,3,5*/ [maxvalue n | nomaxvalue] [minvalue n | nominvalue] [noorder|order]/*多線程,單線程*/ [nocycle] www.2cto.com [cache n]; /*緩衝*/ --刪除序列 drop sequence sequence_name; --更改序列 1 3 5 alter sequence sequence_name increment by 2 maxvalue 80 minvalue 1 order nocycle cache 2;