首页 » ORACLE » oracle 表添加主键 primary key

oracle 表添加主键 primary key

根据数据库三范式就是每个表建议要有主键,每个字段不可再分,表与之间不存在部分依赖

数据库的优化首先考虑的也是主键

主键会在对应的字段加唯一约束、加not null,建 索引

怎么为表加主键呢

1,建表同时

SQL> create table test13 (id int primary key);

Table created.

2,建表后加字段时

SQL> alter table test12 add id2 int primary key;

Table altered.
3,主键字段存在时

SQL> select constraint_name from user_constraints where table_name=’TEST12′;

CONSTRAINT_NAME
————————————————————
SYS_C0010610

SQL> alter table test12 drop constraint SYS_C0010610
2  ;

Table altered.

SQL> alter table test12 add id1 int;

Table altered.

SQL> alter table test12 add constraint pk_id1_t12  primary key(id1);

Table altered.

完成!

ps:如果在要加主键的字段的值中有空值或不唯一,就会报错,有空值时报

SQL> alter table test12 add constraint pk_id1_t12  primary key(id1);
alter table test12 add constraint pk_id1_t12  primary key(id1)
*
ERROR at line 1:
ORA-01449: column contains NULL values; cannot alter to NOT NULL

打赏

目前这篇文章有1条评论(Rss)评论关闭。

  1. Guadalupe Lumantas | #1
    2011-12-21 at 03:23

    Always bear in mind that your own resolution to succeed is more important than any other.