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

 

 




 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM