--维护数据的完整性 “约束”
--创建一张表
create table test1
(test1ID int primary key identity(1,1), --主键值自增长模式,插入(insert)时可以不指定主键值
testname nvarchar(30) not null, --不为空
testpass nvarchar(30) not null,
testage int --不写not null表示可以为空
)
insert into test1 (testage) values(3) --报错,因为没有给不能为空的两个字段testname和testpass指定值
insert into test1 (testname,testpass,testage) values('','',5) --成功,表格里没有任何显示(与NULL是不同的)
------------------------------------------------知识点-------------------------------------------------------
--1. not null(非空):插入数据时,必须为其提供数据
--2. unique(唯一):当定义了唯一约束后,该列值是不能重复的,但是可以为null(null也只能有一个)
--3. primary key(主键):用于唯一标识表行的数据,定义主键后,该列值不能重复且不能为null
--说明:一张表最多只能有一个主键,但可以有多个unique约束。
--4. 表可以有复合主键(多列组合而成)
-------------------------------------------------END---------------------------------------------------------
--复合主键 primary key (字段1,字段2,...)
create table test3
(testID int,
testname nvarchar(30),
testpass nvarchar(30),
testage int,
primary key (testID,testname) --表级定义
--test1ID int primary key identity(1,1) --行级定义
)
--外键(foreign key)
--主表的某一行可以被从表的多个行指向,但从表的某一行只能指向主表的某一特定行(不能一行对多行)
--check的使用:用于设定字段值的范围
create table test4
(testID int,
testname nvarchar(30),
testpass nvarchar(30),
sal int check (sal>=1000 and sal<=2000) --规定sal的值1000-2000(check)
)
select * from test4
insert into test4 values(1,'haha','xy',2500) --出错
--default的使用:如果没有显示指定某个字段的值,就是用default的值;否则,保存的是显示指定的值。
create table mess
(messID int primary key identity(1,1),
mescon nvarchar(200) not null,
mesDate datetime default getdate()
)
select * from mess
insert into mess (mescon) values('哈喽,周末有空吗?')
insert into mess (mescon,mesDate) values('有呀,约起!','2017-10-20')
------------------------------案例(使用上面的所有知识点)----------------------------------
--商品表
create table goods
(goodsId nvarchar(50) primary key,
goodsName nvarchar(80) not null,
unitprice numeric(10,2) check (unitprice>0),
category nvarchar(3) check (category in('食物','日用品')),
provider nvarchar(50)
)
--客户表
create table customer
(customerId nvarchar(50) primary key,
cusName nvarchar(50) not null,
address nvarchar(100),
email nvarchar(100) unique,
sex nchar(1) check (sex in('男','女')) default '男',
cardId nvarchar(18)
)
--购买表
create table purchase
(customerId nvarchar(50) foreign key references customer(customerId),
goodsId nvarchar(50) foreign key references goods(goodsId),
nums int check (nums>0)
)
-------------------------------------案例END----------------------------------
07-30
07-30
07-30
07-30