(火炬)MS SQL Server数据库案例教程(二)
ull,
R_name char(8) not null default getdate(),--该列的默认值取系统的当前的日期
R_date datetime not null
)
或
Alter table rec
Add constraint df_date defaut getdate() for R_date
12.check 约束
Create table rec ( R_id char(5) not null, R_name char(8) not null, R_sex char(2) check(sex=’男’ or sex=’女’),--check 约束 值必须是 男或女 这两个任意一个值 R_DATE datetime not null Rid char(18), Constraint ck_rec_rid check (len(Rid)=18 or len(Rid)=15)—check约束 身份证值的长度只能为18或15这两个任意一个长度 )
或 添加check约束
Alter table rec
Add Constraint ck_rec_rid check (len(Rid)=18 or len(Rid)=15)
与
Alter table rec
Add Constraint ck_rec_sex check (sex=’男’ or sex=’女’)
13.unique 唯一约束
Create table rec ( R_id char(5) not null, R_name char(8) not null, R_sex char(2) check(sex=’男’ or sex=’女’),--check 约束 值必须是 男或女 这两个任意一个值 R_DATE datetime not null Rid char(18) unique, )
或
Alter table rec
Add constrater un_Rid unique(pid)—限定身份证号码唯一,不会重复出现
14.foreign key 外键约束
作用是 学生表与教师表人的信息相关联 ,t_id列与R_id列定义foreign ke 约束
Create table courses ( t_id char(5) not null foreign key references t_p(t_id),--与t_p表相关联 列级约束 R_id char(5) not null, Grade char(16), Class char(10), Constraint fk_course_rec_R_id foreign key(R_id) references Rec(R_id)—与rec表相关联 表级约束 )
或
Alter table course Add Constraint fk_course_rec_R_id foreign key(R_id) references Rec(R_id) —与rec表相关联 Alter table course Add constraint fk_course_t_p_t_id foreign key(t_id) references t_p(t_id) --与t_p表相关联
知识点:
(1)与外键列t_id和r_id 列相对应的相关表中的列(学生表中t_id列和老师表中r_id列)必须定义为primary key约束或unique约束
(2)在建立外键时,外键列t_id和r_id列的数据类型及长度必须与相对应的相关表中的主键列(学生表中t_id列和老师表中r_id列)的数据类型及长度一致或者可以由SQL Server自动转换。
15.删除约束
删除R_id 列上名为ck_rec_rid的check约束
Alter table t_p
Drop constraint ck_rec_rid
对于创建时没有指定名称的约束,例如,学生信息表中sex列上创建的check约束,可以先使用如下的命令,查找到约束的名称。
Exec sp_constraint t_p或Exec sp_help constraint t_p
根据上面的语句执行后 找到想要的约束名称
再
alter table t_p
drop constraint ck_t_p_sex_1367E606
16创建索引
(1)非聚集索引—在stud表上创建名为studid_ind的聚集索引
Create clustered index studid_ind on stud(studid)
注释:一个表里只有一个聚集索引。
(2)非聚集索引—在stud表上创建名为studfullname_ind的非聚集索引
Create unique index studfullname_ind on stud(fname desc,lname) 唯一索引
Create nonclustered index studfullname_ind on stud(fname desc,lname)非聚集索引
注释:非聚集唯一索引 desc 降序 (去掉non 为聚集索引)
用“,”号隔开可以进行建立多个列的索引
17.查看stud表的索引
Select sp_helpindex stud
18.使用索引
Select * from stud (index=studid_ind) where id=’2007
19.删除索引
(1)drop index stud.studid_ind
20.修改stud表,设定studid为主键
Alter table stud
Constraint pk_studid primary key clustered(studid)
直接删除主键约束的pk_studid 索引 会报错
21.重建索引
(1)重建pk_studid索引
Dbcc dbreindex (stud,pk_studid)
注释:dbcc 重建索引命令 dbreindex 重建的标示
(2)重建pk_studid 索引,设定其填充因子占50%
Dbcc dbreindex (stud,pk_studid,50)
(3)重建studname_ind 索引
Create index studname_id on stud(fname,lname) with drop_existing
提示:
因为非聚集索引包含聚集索引,所以在去除聚集索引时,必须重建非聚集索引。如果重建聚集索引,则必须