SQLServer 主鍵、外鍵、唯一等約束


主鍵(primary key)約束、外鍵(foreign key)約束、唯一(unique)約束、檢查(check)約束、默認值(default)約束實例

Oracle 有如下類型的約束:
NOT NULL(非空)、UNIQUE Key(唯一約束)、PRIMARY KEY(主鍵約束)、FOREIGN KEY(外鍵約束)、CHECK約束
Oracle使用SYS_Cn格式命名約束.
創建約束:在建表的同時創建、建表后創建
約束的類型有如下幾種:
C (check constraint on a table) 
P (primary key) 
U (unique key) 
R (Referential AKA Foreign Key) 
V (with check option, on a view) 
O (with read only, on a view)
1、創建約束
CREATE TABLE students(
student_id VARCHAR2(10) NOT NULL,
student_name VARCHAR2(30) NOT NULL,
college_major VARCHAR2(15) NOT NULL,
status VARCHAR2(20) NOT NULL,
state VARCHAR2(2),
license_no VARCHAR2(30)
) TABLESPACE student_data;
2、創建主鍵: 
ALTER TABLE students ADD CONSTRAINT pk_students PRIMARY KEY (student_id) 
USING INDEX TABLESPACE student_index;
Alter table table_name add constrants BID primary key (bookno);
ALERT TABLE table_name MODIFY( column1 PRIMARY KEY);
3、創建Unique約束:
ALTER TABLE students ADD CONSTRAINT uk_students_license UNIQUE (state, license_no)
USING INDEX TABLESPACE student_index;
4、創建Check約束:定義每一記錄都要滿足的條件,條件表達式不允許有:CURRVAL, NEXTVAL, LEVEL, ROWNUM,SYSDATE, UID, USER, USERENV 函數:
ALTER TABLE students ADD CONSTRAINT ck_students_st_lic CHECK ((state IS NULL AND license_no IS NULL) OR (state IS NOT NULL AND license_no is NOT NULL));
添加check約束(check_1為約束名,dept_salary為字段名 )     
alter table emp add constraint check_1 check(dept_salary>0);       
5、創建外鍵約束:
ALTER TABLE students ADD CONSTRAINT fk_students_state FOREIGN KEY (state) REFERENCES state_lookup (state);
6. 創建不能為空約束 not null
alter table table_name modify(name not null);
alter table table_name modify name1 varchar2(20) not null;

實例1:
首先創建學生信息表studentinfo和學生成績表testinfo。 
--學生信息表 
CREATE TABLE studentInfo ( 
stuNo CHAR(10) NOT NULL , 
stuName VARCHAR2(20) NOT NULL, 
stuSex NUMBER(1), 
stuBirthday DATE DEFAULT SYSDATE , 
stuAddress VARCHAR2(20) 
); 
--學生成績表 
CREATE TABLE testInfo ( 
stuNo CHAR(10) NOT NULL , 
classNo CHAR(5) NOT NULL, 
testScore NUMBER(3,1) 
); 
--約束條件:設置主鍵 
alter table testinfo add constraint fk_1 foreign key (stuno) references studentinfo(stuno); 
--約束條件:設置外鍵 
alter table studentinfo add constraint pk_1 primary key (stuno); 
--約束條件:設置唯一 
alter table testinfo add constraint uniq_1 unique (stuno,classno);

主鍵、外鍵、唯一約束、check約束、非空約束等約束詳解實例:
1、--創建表
create table tb_Dept
(
Deptid char(2) Primary key,
DeptName char(16) Not Null
)
2、--外鍵約束
create table tb_Student
(
Studid char(10) Primary key,
Studname char(8) Not null,
Deptid char(2) Not null,
Constraint FK_DeptID Foreign Key (Deptid)
References Tb_Dept(DeptID)
)
3、--外鍵約束簡化形式,必須要求tb_Dept表中DeptID為主鍵,且數值類型相同
create table Tb_Student
(
StudId char(10) Primary key,
StudName char(8) Not null,
DeptID char(2) not null References Tb_Dept
)
4、--創建表,無主鍵
create table Tb_Class
(
ClassID char(8) not null,
ClassName varchar(30) not null,
DeptId char(2) not null,
ClassStuNumber int
)
5、--創建表,同時定義主鍵
create table Tb_Class
(
classid char(8) not null,
ClassName varchar(30) not null,
DeptID char(2) not null,
ClassStuNumber int
constraint PK_ClassID Primary key
(ClassID,ClassName)
)
6、--新增主鍵
Alter table Tb_class ADD Constraint PK_ClassID primary key(Classid)
7、--刪除主鍵
Alter table tb_Class Delete Constraint PK_ClassID Primary key(ClassID)
8、--外鍵級聯更新,刪除,簡化形式
Create table tb_student
(
studID char(10) Primary key,
StudName char(10) not null,
DeptID char(2) not null References tb_Dept 
On Update cascade 
on delete cascade
)
9、--外鍵級聯更新,刪除,標准
create table tb_student
(
studid char(10) Primary key,
StudName char(8) not null,
DeptID char(2) not null,
Constraint FK_Deptid foreign key(DeptID)
References Tb_Dept(DeptID) 
on update Cascade 
on delete cascade 
)
10、--創建無外鍵的表
create table tb_student
(
studId char(10) Primary key,
StudName char(8) not null,
DeptID char(2) not Null
)
11、--給相應的列(DeptID)添加外鍵約束
Alter table tb_Student ADD Constraint FK_DeptID Foreign key(DeptID) References tb_Dept(DeptID)
12、--刪除外鍵約束
Alter table tb_Student Drop Constraint fk_DeptID 
13、--創建表是創建Unique約束
Create table tb_Student
(
studId char(10) Primary key,
Studname char(8) not null Unique nonclustered,
DeptID char(2) not null references Tb_Dept
)
create table tb_student
(
studID char(10) Primary key,
Studname char(8) not null,
deptid char(2) not null references tb_dept,
constraint Uk_Stuname Unique(Stuname)
)
14、--創建表結束后,添加、刪除Unique約束
--添加Unique約束
alter table tb_Student ADD Constraint Uk_Depname Unique(Deptname)
15、--刪除unique約束
Alter table tb_student Drop Constraint uk_Depname
16、--創建默認值約束
Create table tb_student
(
stuId char(10) Primary key,
stuName char(8) not null,
DeptID char(2) Not null references tb_Dept,
sex char(2) not null default &#39M',
Birthday smalldatetime not null default getdate()
)
17、--添加默認值約束
alter table tb_student ADD constraint DEF_sex default &#39M' for sex
18、--刪除默認值約束
alter table tb_student Drop Constraint DEF_Sex
19、--創建表時,創建check約束
create table tb_student
(
StudId char(10) Primary key,
Studname char(8) not null,
DeptId char(2) not null references tb_Dept,
sex char(2) not null default &#39M' check(sex in (&#39M',&#39F')),
zipcode char(6) not null check (Zipcode like '[0-9][0-9][0-9][0-9][0-9][0-9]' ),
constraint ck_StudID Check (StudId like &#39S[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')
)
20、--check約束的其他例子
check(coursescore >= 0 and coursescore < = 100)
check(empld like '[A-Z][A-Z][A-Z][1-9][0-9][0-9][0-9][0-9][FM]' or empld like '[A-Z][A-Z][1-9][0-9][0-9][0-9][0-9][FM]')
check(telno in (?',?',?',?',?') or telno like ?[0-9][0-9]')
check(salary between 3000 and 10000)
check(is_manager = 1 and sex = &#39F')
check(case when is_manager<> 1 and sex = &#39F') Then 1 Else 0 End = 0 
21、--添加check約束
alter table tb_student with nocheck ADD Constraint ck_Sex check(sex in (&#39M',&#39F'))
22、--刪除check約束
alter table tb_student Drop constraint ck_sex

數據完整性總結
1、--Primary key 約束
--非聚集索引不超過個,聚集索引最多個
--primary key未指定索引,索引類型與Unique相同
--Primary key的所有列必須非空not null
2、--Unique約束
--默認使用nonclustered
--每個Unique都生成一個索引,非聚集索引不超過,聚集索引最多個
3、--Foreign key
--Foreign key列輸入非空值,該值必須在被引用列中存在
--Foreign key約束僅能引用同一服務器的數據庫表,跨數據庫的引用必須通過觸發器實現
--列級的Foreign key約束的references子句只能列出一個引用列,且數據類型必須相同
--表級Foreign key約束的references子句引用列的數目必須與約束列的列數相同,沒個列的數據類型必須相同
--類型為timestamp的列是外鍵、被引用鍵的部分,不能指定cascade、set Null、set default
--臨時表不強制Foreign key約束
--Foreign key只能引用所引用的表的Primary key或unique 約束中的列,或引用的表上的Unique Index中的列
4、--Default定義
--每列只能有一個Default定義
--Default定義可以包含常量值,函數,或Null
--不能對類型為timestamp的列,或自增長型的列,創建Default定義
5、--Check約束
--列級Check約束只能引用被約束的列,表級Check約束只能引用同一表中的列
--不能在text、ntext、或image列上定義check約束
6、--其他約束相關信息
--為約束創建的索引不能用Drop Index刪除,必須用Alter table刪除約束
--如果某個表有約束以及觸發器,則將在觸發器執行前先檢查約束條件
--若要獲得關於表及其列的報表,請使用sp_help或sp_helpconstraint表名
--若要獲得與表相關的視圖和存儲過程的報表,請使用sp_depends
--若列為計算列,是否為空由系統確定。使用帶AllowsNull屬性的ColumnProperty函數


免責聲明!

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



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