读书人

oracle主键从增长

发布时间: 2012-08-29 08:40:14 作者: rapoo

oracle主键自增长

1、比较土鳖的方式

定义主键number类型,之后每次存数据时候,id为取得此表的max(id),之后+1,在存放进去
可以用时间作为主键,唯一。

2、官方版

使用序列方式,增长主键。下面介绍使用过程。

创建测试表 t

SQL> create table t(  2  id number(10) primary key,  3  name varchar2(20) not null); Table created


创建序列sequence t_id

SQL> create sequence t_id  2  start with 2          --以2开始  3  increment by 2;       --以2为自增长1、3、5、7... Sequence created


使用序列

SQL> insert into t values(t_id.nextval,'人1'); 1 row inserted SQL> insert into t values(t_id.nextval,'人1'); 1 row inserted 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> select * from t;          ID NAME----------- --------------------          2 人1          4 人1          6 人1          8 人1

删除表数据删除表

SQL> truncate table t; Table truncated SQL> drop table t; Table dropped


恢复删除表

flashback table t to before drop;

序列详情介绍

--序列    /*     *需求:在插入记录时,主键值,需要不重复而且唯一,     *它的值靠人工生成不太靠普,所以我们需要一个能生成值的一个东西,     *这个东西就是序列,序列是一个数据库对象。生成序列的语法:     */    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]     [cache n]; /*缓存*/    --删除序列    drop sequence sequence_name;    --更改序列 1 3 5    alter sequence sequence_name    increment by 2    maxvalue 80    minvalue 1    order    nocycle    cache 2; 


读书人网 >编程

热点推荐