--======================
--author:_yeeXun
--date:12/29/2010 10:18:00 AM
--address:Jau 17-304
--======================
商店售货系统设计
现有一个商店的数据库,记录客户及其购物情况,有下面三个表组成:
商品goods(商品号goodsId,商品名goodsName,单价unitprice,商品类别category,供应商provider);
客户表customer(客户号customerId,姓名name,住址address,电邮email,性别sex,省份证cardID);
购买purchase(客户号customerId,商品号goodsId,购买数量nums);
用sql语言完成下列功能:
1.建表,在定义中要求声明:
a) 每个表的主键
b) 客户的姓名不能为空
c) 单价必须大于0,购买数量必须在1~30之间
d) 电邮不能重复
e) 客户的性别必须是男或者女,默认为男
Goods表
SQL> create table goods(goodsId char(8) primary key,
2 goodsName varchar2(30),
3 unitprice number(10,2) check(unitprice >0),
4 category varchar2(8),
5 provider varchar2(30));
Table created
Customer表
SQL> create table customer(customerId char(8) primary key,
2 name varchar2(50) not null,
3 address varchar2(50),
4 email varchar2(50) unique,
5 sex char(2) default '男' check(sex in('男','女')),
6 cardId char(18) );
Table created
Purchase表
SQL> create table purchase( customerId char(8) references customer(customerId),
2 goodsId char(8) references goods(goodsId),
3 nums number(10) check(nums between 1 and 30) );
Table created
如果在建立表时忘记建立必要的约束,则可以在建表后使用alter table命令为表增加约束。但是注意,增加not null约束时,需要使用modify选项,而增加其他四种约束使用add选项。
2.修改表
a)每个表的主外码
b)客户的姓名不能为空;增加商品名也不能为空
SQL> alter table goods modify goodsName not null;
Table altered
c)单价必须大于0,购买数量必须在1~30之间
d)电邮不能重复;增加省份证不能重复
SQL> alter table customer add constraint cardUnique unique(cardId);
Table altered
e)客户的性别必须是男或者女,默认为男
f)增加客户的住址只能是海淀、朝阳、东城、西城、通州、崇文。
SQL> alter table customer add constraint addressCheck check(address in('东城','西城','海淀','朝阳','通州','崇文'));
Table altered