–在mysales数据库中创建goods表
use mysales
create table goods
(商品编号 int not null,
商品名称 varchar(20) not null,
生产厂商 varchar(20) not null,
进货价 money not null,
零售价 money not null,
数量 int not null,
进货时间 datetime not null,
进货员工编号 char(6) not null)
–创建employees表格
create table employees
(编号 char(6) not null,
姓名 char(8) not null,
性别 bit not null,
部门 varchar(16),
电话 varchar(20),
地址 varchar(50))
主键约束
为goods表中的“商品编号”列创建主键约束
以保证不会出现编号相同的商品
alter table goods
add constraint pk_goodsno primary key(商品编号)
惟一值约束
为employees表创建名为ix_employeesname的惟一值约束
alter table employees
add constraint ix_employeesname unique(姓名)
默认约束
为goods表创建df_goodsdate的default约束
使“进货时间”列的默认值为当前的日期
alter table goods
add constraint df_goodsdate default(getdate()) for 进货时间
检查约束
限定employees表的“部门”这一列只能从“财务部”、“销售部”、“采购部”、“库存部”四个部门中选择一个
alter table employees
add constraint ck_employeesdep check (部门='财务部' or 部门 = '库存部' or 部门 = '销售部' or 部门='采购部')
外键约束
(外键:编号在employees中是主键,在goods表中不是主键,是外键,所以应该把employees中的主键建立好)
–进货员工编号和编号的数据类型应保持一致
–为goods表创建名为fk_goods_employees的foreign key(外键)约束
–该约束限制“进货员工编号”列的数据只能是employees表“编号”列中存在的数据
alter table goods
add constraint fk_goods_employees foreign key (进货员工编号) references employees(编号)
–删除外键约束
(同理可得,换掉约束名,也可以删掉其他约束)
ALTER TABLE goods
DROP CONSTRAINT fk_goods_employees
–禁(启)用约束
仅适用于外键和检查约束
alter table employees
nocheck constraint ck_employeesdep
alter table employees
check constraint ck_employeesdep
–创建sell表,同时进行约束的设置
create table sell
(销售编号 int not null primary key identity(1,1),
商品编号 int not null references goods(商品编号),
数量 int not null check(数量>0),
售出时间 datetime not null default(getdate()),
售货员工编号 char(6) not null,
constraint fk_sell_employees foreign key (售货员工编号) references employees(编号)
)
–查看约束
exec sp_helpconstraint employees
增加一列
给employees表增加一列,列名为“邮箱”,数据类型为varchar(20)
alter table myemployees
add 邮箱 varchar(20)
–删除一整列
alter table employees
drop column 邮箱
–重命名表
execute sp_rename 'employees','myemployees'
–删除表
drop table myemployees
–插入数据
insert goods values(1,'篮球','asidas',100,200,20,default,'000002')
insert into myemployees(编号,姓名,性别)
values('1304','李明',1)
–查看表
select * from goods
select * from myemployees
–修改数据
update myemployees
set 电话='07713836386'
where 编号='1304'