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

来源:互联网 发布:seo 教程 编辑:程序博客网 时间:2024/05/19 17:57
--约束--维护数据的完整性--创建一张表create table test1(test1Id int primary key identity(1,1),test1Name varchar(30) not null,test1Pass varchar(30) not null,testAge int)drop table test1insert into test1  values('','','')select *from test1create 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 test2drop 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