資料庫完整性及約束,資料庫完整性條件約束

來源:互聯網
上載者:User

資料庫完整性及約束,資料庫完整性條件約束

轉載請註明出自朱朱家園http://blog.csdn.net/zhgl7688

資料庫完整性及約束

1、  資料完整性:常用三種類型的約束保證資料完整性有域(列)完整性、實體完整性、參考完整性。

2、  實體完整性:能夠唯一標識表中的第一個記錄。

保證方法有主鍵約束、標識約束、唯一約束。

主鍵約束與唯一約束添加的基本文法

Alter  table  表名 addconstraint  約束名  約束類型  具體的約束說明

約束名的取名規則:約束類型_限制欄位。

比如主鍵(Primary Key)約束:PK_StuNo,唯一(Unique Key)約束UQ_StuIdNo。

alter tablestudents  

add constraintPK_StudentId primarykey (StudentId)

alter tableStudents

add constraintUQ_StudnetNo unique(studentNo)

3、  值域完整性:表中特定列資料的有效性,確保不會輸入無效的值。

保證方法有檢查約束、限制資料類型、預設值、非空約束。

約束名的取名規則:檢查(check key)約束:CK_Age;預設(default key)約束:DF_Address。

alter tablestudents

add constraintCK_Age check (agebetween 15 and 28)

alter tablestudents

add constraintDF_Address default ('地址不詳')for Address

4、  參考完整性:維護表間資料的有效性、完整性。

約束方法:建立外鍵,關聯另一表的主鍵,即外鍵約束

約束名的取名規則:外鍵(foreign key)約束:FK_LoginId

alter tablestudents

add constraintFk_LoginId foreignkey(classid)references studentclass(classid)

5、  外鍵的使用:要求資料類型、資料長度必須與對應的主鍵表欄位完全一致;添加資料時,要首先添加主鍵表,再添加外鍵表;刪除資料時,要首先刪除外鍵表資料,再刪除主鍵表資料。

6、  完整資料庫建立步驟:

建庫—》建表—》主鍵約束—》值域完整性約束—》外鍵約束

轉載請註明出自朱朱家園http://blog.csdn.net/zhgl7688

相關文章

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.