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
复制代码

 

 




 

posted @   CS讷于言而敏于行  阅读(1649)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示