oracle主键的修改 Oracle主键自动增长的设置

oracle主键的修改  Oracle主键自动增长的设置 

1、创建表的同时创建主键约束

(1)无命名

create table student (

studentid int primary key not null,

studentname varchar(8),

age int);

(2)有命名

create table students (

   studentid int ,

   studentname varchar(8),

   age int,

   constraint yy primary key(studentid));

2、删除表中已有的主键约束

(1)有命名

alter table students drop constraint yy;

(2)无命名

可用 SELECT   *   from   user_cons_columns;

查找表中主键名称得student表中的主键名为SYS_C002715

alter table students drop constraint SYS_C002715;

3、向表中添加主键约束

alter table students add constraint pk_students primary key(studentid);

4、为主键设置自增长

在Oracle中,可以为每张表的主键创建一个单独的序列,然后从这个序列中获取自动增加的标识符,把它赋值给主键。例如一下语句创建了一个名为customer_id_seq的序列,这个序列的起始值为1,增量为2。

create sequence customer_id_seq increment by 2 start with 1

一旦定义了customer_id_seq序列,就可以访问序列的curval和nextval属性。

curval:返回序列的当前值

nextval:先增加序列的值,然后返回序列值

以下sql语句先创建了customers表,然后插入两条记录,在插入时设定了id和name字段的值,其中id字段的值来自于customer_id_seq序列。最后查询customers表中的id字段。

create table customers(id int primary key not null, name varchar(15));

insert into customers values(customer_id_seq.nextval, 'name1');

insert into customers values(customer_id_seq.nextval, 'name2');

select id from customers;

oracle主键的修改  Oracle主键自动增长的设置 

猜你喜欢

转载自java161.iteye.com/blog/1867802