10. SQL -- 约束
一个成功的数据库必须对这些数据进行定义,使它们符合现实,具有完整性,那么这里完整性,就是我们所说的约束.约束实际上就是使数据完整,也就是存储的数据具有一致性和正确性,为了使我们的数据完整,sql server 2005定义了相应的检查和控制数据完整的一套机制,根据所对应的数据库对象和范围的不同,可以分为实体完整,域完整,参照完整和用户自定义完整4种,这4种完整性的涵义在这里我就不多说了,具体大家可以看书.
约束在实现时,可以通过以下来实现,主要包括 primary key,check,unique,default,foreign key.
那么下面我们就来看看如何在sql server2005中实现以上5种约束.
一,建立student 数据库,方法有两种,这里我们用也就是sql语句来实现,语句如下:
Create database student
写完后按f5执行,数据库就可以了,
二,建立两张表,一个是学生资料表(stuinfo),和学生成绩表(stucj),sql语句如下:
Stuinfo表:
create table stuinfo
(
stuid char(8) not null,
stuname nvarchar(10),
stusex nvarchar(2),
stuage tinyint,
stuaddr varchar(50),
stutel varchar(15),
stuintro varchar(200)
)
Stucj表:
create table stucj
(
stuid char(8) not null,
stuname nvarchar(10),
chinese numeric(4,1),
english numeric(4,1),
math numeric(4,1)
)
三, primary key(主键约束)指的是唯一能将所有记录区分开的字段,以上两张表中的stuid(学生学号)可以作为主键,定义语句是:
use student
go
alter table stuinfo
add constraint pri_id1 primary key(stuid)
alter table stucj
add constraint pri_id2 primary key(stuid)
四.Check(核对)约束,指的是限制一列和多列所输入的值的范围。表中shuage字段表示的是学生的年龄,对这个字段我们可以设置它的范围,sql 语句如下:
Use student
Go
Alter table stuinfo
Add constraint ch_age check(stuage>10 and stuage10 and stuage
页:
[1]