SQl -维护数据的完整性--约束 -

--约束
--维护数据的完整性

--创建一张表
create table test1
(test1Id int primary key identity(1,1),
test1Name varchar(30) not null,
test1Pass varchar(30) not null,
testAge int
)
drop table test1
insert into test1  values('','','')

select *from test1



create table test2
(test2Id int primary key identity(1,1),--主键和自增长
test2Name varchar(30)  unique,--唯一
test2Pass varchar(30) not null,--不为空
test2Age int
)

insert into test2 (test2Name,test2Pass,test2Age) values('xx','456',12)
insert into test2 (test2Name,test2Pass,test2Age) values('cc','456',12)
select *from test2
drop table test2


--复合主键,只有当test3Id和test3Name同时相等时才算重复
create table test3
(test3Id int ,
test3Name varchar(30)  ,
test3Pass varchar(30) ,
test3Age int,
primary key(test3Id,test3Name)
)




--default使用
create table mes
(mesId int primary key identity(1,1),
mescon varchar(2000) not null,
mesDate datetime default getdate(),
)


insert into mes(mescon) values('你好呀')
insert into mes(mescon,mesDate) values('呵呵','')


select *from mes




--商品goods(商品号goodsId,商品名goodName
--单价unitprice,商品类别category,供应商provider)
--客户customer(客户号customerId,姓名name,住址adress,电邮email
--性别sex,身份证carId)
--购买purchase(客户号customerId,商品号goodsId,购买数量nums)
--请用SQL语言完成下列功能
--1、建表,在定义中要求声明:
--(1)每个表的主外键
--(2)客户的姓名不能为空
--(3)单价必须大于0,购买数量必须在1-30之间
--(4)电邮不能够重复
--(5)客户的姓名必须是男或者是女,默认是男
--(6)商品类别是‘食物’‘日用品’ 
--建立goods表,Numeric(10,2) 指字段是数字型,长度为10 小数为两位的 
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)
)

select *from goods

--建立customer表
create table customer
(customerId  nvarchar(50) primary key,
cusname nvarchar(50) not null,
adress nvarchar(100),
email nvarchar(100) unique,
sex nchar(1) check(sex in('男','女')) default '男',
carId nvarchar(50))


select *from customer

--建立purchase表
create table purchase
(customerId nvarchar(50) foreign key references customer(customerId),
	goodsId nvarchar(50) foreign key references goods(goodsId),
	nums int check(nums>0)
	)

select *from purchase

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值