欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Oracle 创建数据表以及对数据表、字段、主外键、约束的操作

发布时间:2025/7/14 编程问答 51 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Oracle 创建数据表以及对数据表、字段、主外键、约束的操作 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

选择主键的原则:

  • 最少性
  • 尽量选择使用单个键作为主键
  • 稳定性
  • 尽量选择数值更新少的列作为主键


1、创建数据表(CREATE TABLE)

--创建数据表Student create table Student( SID number(2) constraint PK_SID primary key,--指定该列为主键列,并指定主键名为PK_SID SName varchar2(16) not null )--创建数据表Class create table Class( CID number(2) constraint PK_CID primary key,--指定该列为主键列,并指定主键名为PK_CID CName varchar2(16) not null )

2、重命名、删除数据表

--将数据表Student重命名为Stu alter table Student rename to Stu;
--删除数据表Student
drop table Student;

3、添加、重命名、删除字段、修改字段数据类型

--为数据表Student添加字段SGender和SCID alter table Student add (SGender char(2)); alter table Student add (SCID number(2)); --删除数据表Student中的字段SGender alter table Student drop column SGender; --将数据表Student中的字段SID重命名为StuID alter table Student rename column SID to StuID; --修改数据表Student中字段SID的数据类型 alter table Student modify SID number(2);

4、添加、删除字段约束

--为数据表Student中的字段SGender添加约束,并指定该约束的名称为ch_gender,指定该列的值只能是'男'或'女' alter table Student add constraint ch_gender check(SGender='' or SGender=''); --删除数据表Student中约束名为ch_gender的约束 alter table Student drop constraint ch_gender;

5、查看、添加、重命名、删除、禁用、启用主键

--查看数据表Student中已定义的主键 select * from user_cons_columns where table_name='STUDENT'; --将数据表Student中的字段SName设为主键列,并指定该主键的名称为PK_Name alter table Student add constraint PK_Name primary key(SName); --删除主键名为PK_Name的主键 alter table Student drop constraint PK_Name; --将主键名PK_StuID重命名为PK_SID alter table Student rename constraint PK_StuID to PK_SID; --禁用主键 alter table Student disable primary key; --启用主键 alter table Student enable primary key;

 6、查看、添加、重命名、删除、禁用、启用外键

--查看数据表中已存在的外键 select owner,constraint_name from user_constraints where constraint_type='R'--P 主键 R 外键 --添加外键 alter table Student add constraint FK_SCID foreign key(SCID) references Class(CID) --删除外键 alter table Student drop constraint FK_SCID --重命名外键 alter table Student rename constraint FK_SClassID to FK_SCID --禁用外键 alter table Student disable constraint FK_SCID --启用外键 alter table Student enable constraint FK_SCID

 

 




 

转载于:https://www.cnblogs.com/cs569/p/7469272.html

总结

以上是生活随笔为你收集整理的Oracle 创建数据表以及对数据表、字段、主外键、约束的操作的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。