Oracle資料庫的欄位約束建立和維護

來源:互聯網
上載者:User

建立Oracle資料庫的欄位約束:

非空約束
唯一約束
對欄位的取值的約束
預設值
外鍵約束

create table tab_class(
 class_id number primary key,
 class_name varchar2(10) not null unique
);

create table tab_stu(
stu_id number,
 --學生姓名,不可為空,不能重複
stu_name varchar2(20) not null unique,
 --學生姓名只能是male或female
stu_gender varchar2(6) not null check(stu_gender='male' or stu_gender='female'),
 --學生年齡只能在18到60之間
stu_age number check(stu_age >18 and stu_age <60),
 --郵箱可以不填寫,填寫的話不能相同
stu_email varchar2(30) unique,
stu_address varchar2(30),
--外鍵約束
class_id number not null references tab_class(class_id)
);

維護已經建立好的約束:

可添加或刪除約束,但不能直接修改。
可使約束啟用和禁用。
非空約束必須使用MODIFY子句增加。
為表增加主鍵約束:

--維護約束
--建立約束
create table tab_check(
 che_id number,
 che_name varchar2(20)
);
--為表增加主鍵約束
alter table tab_check
add constraints tab_check primary key(che_id);

--添加唯一約束,tab_check_unique表示約束的名稱
alter table tab_check
add constraints tab_check_unique unique(che_name);

添加檢查約束:

--添加一個欄位
alter table tab_check
add che_age number;
--添加檢查約束
alter table tab_check
add constraints tab_check_age check(che_age>18 and che_age<60);

--刪除主鍵約束
alter table tab_check
drop constraints tab_check;

--禁用約束
alter table tab_check disable constraints tab_check;

--啟用約束
alter table tab_check enable constraints tab_check;

複合約束,聯合主鍵,也就是兩個欄位的組合成一個主鍵

--聯合主鍵
create table tab_person(
 tab_firstname varchar2(10),
 tab_lastname varchar2(10),
 tab_gender varchar2(5),
 primary key(tab_firstname,tab_lastname)
);

為表添加外鍵約束:

alter table tab_stu
add constraints tab_stu foreign key(class_id) references tab_class(class_id);

Oracle完整性條件約束

Oracle的約束和索引

從Oracle的約束到索引

Oracle常用資料類型和完整性條件約束

ORA-02291: 違反完整約束條件 …… - 未找到父項關鍵字

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.