修改主键的方法:1、利用“alter table 表名 drop constraint 主键名;”语句删除主键;2、使用“alter table 表名 add primary key(字段);”语句添加主键。
本教程操作环境:windows7系统、oracle 11g版、dell g3电脑。
主键解释:
一个表的唯一关键字 比如一个学生表 学号不能重复且唯一 ,学号就是关键字,即为主键。
区别于外键:
外键就是跟其他表联系的字段 ,还是比如有一张学生表 还有一张选课表,这个时候要修改学生表中的学号 ,选课表里对应的就也得变,这样就需要给选课表加学号作为外键约束,这样当你修改学号时 所有外键关联的就都改了
主键的添加、删除等操作1.有命名主键
1)有命名主键的添加
①建表时添加主键(yy为主键“id”的主键名称)
create table table_test( id int not null, --注意:主键必须非空 name varchar(20) not null, address varchar(20), constraint yy primary key(id) );
②建表后添加主键
alter table table_test add constraint yy primary key(id);
公式:alter table 表名 add constraint 主键名 primary key(字段);
2)有命名主键的删除
alter table table_test drop constraint yy;
公式:alter table 表名drop constraint 主键名;
3)有命名主键的修改
需先删除主键,再进行添加
2.无命名主键
1)无命名主键的创建
①建表时添加主键(主键“id”的主键名称需要查询出来,下文有方法)
create table table_test(id int not null, --注意:主键必须非空name varchar(20) not null,address varchar(20),primary key(id));
②建表后添加主键
alter table table_test add primary key (id);
公式:alter table 表名 add primary key(主键字段1,主键字段2...);
2)无命名主键的删除
①先查出来主键名(constraint_name),user_cons_columns表会在文末给出解释
select t.* from user_cons_columns t where t.table_name = 'table_test' and t.position is not null;
公式:select t.* from user_cons_columns t where t.table_name = '表名' and t.position is not null; --表名必须大写,如:table_test
②再执行删除的sql
alter table table_test drop constraint sys_c0056038;
公式:alter table 表名 drop constraint 主键名;
3)无命名主键的修改
需先删除主键,再进行添加
推荐教程:《oracle教程》
以上就是oracle怎么修改主键的详细内容。