第一天
--数据库的应用
--数据库由物理结构和逻辑结构组成
--物理结构由两个文件组成:数据文件和日志文件逻辑文件由数据库软件进行维护
--1创建数据库分号表示一段程序的结束逗号表示程序的转折
createdatabase db2;--创建的数据库属性文件都是默认的值
--指定相应数据库属性文件的大小
createdatabase db3 --创建数据库名称(db3)
on(
name ='db3',--数据库的名称
--数据库文件的存放地址
filename='C:\Program Files\Microsoft SQLServer\MSSQL.1\MSSQL\Data.db3.mdf',
size=5,--指定文件的大小
maxsize=10,--文件的最大值
filegrowth=3--数据库文件的增量
)
logon--日志文件
(
name='db3_log',--日志文件的逻辑名
--日志文件的存放地址(一般和数据文件放在一起)
filename='C:\Program Files\Microsoft SQLServer\MSSQL.1\MSSQL\Data.db3.ldf',
size=3,
maxsize=10,
filegrowth=2
);
--删除数据库
dropdatabase db2;
--使用数据库
usedb3;
--创建表
--uid表示的是列名int列的数据类型
--identity表示的是列的增量数据函数,列数从开始,每次自增
--primarykey表示表的唯一标识符也称主键
--notnull 表示一个列的非空在进行数据只、自增的时候需要保证此列数据有值
--注意:主键的自动如果自增长的在添加值得时候可以不进行指定否则必须给主键字段手动赋值
--且保证每次的赋值都是唯一的
createtable tb_user
(
uidint primary key not null identity(1,1),
unamevarchar(32),
upassint
);
--常见的数据类型
--整形数据:int bigint samllint tinyint
--浮点型数据:float decimal real
--字符型:char(2) varchar(32)
--时间类型:datetime
--文本类型:text image
单张表的增删查改
-------对单张表的增删改查-----
--增
insertinto tb_user(uname,upass)values('3333',123);
insertinto tb_user(uname,upass)values('lisi',1223);
--查找当前表
select* from tb_user;
selectuname,upass from tb_user;--查询表中的某一列或者多列的数据直接用逗号隔开
selectdistinct[W用1] uname,upass from tb_user;--查询的时候排除相同的数据
--删除
deletefrom tb_user where uid=1;--根据ID删除
truncate[W用2] table tb_user;--清除表的数据
--droptable tb_user; --删除tb_user表
--更新操作
updatetb_user set uname='战神七' where uid=2;
updatetb_user set uname='痛苦女王',upass=123where uid=1;--要更新表中某条数据的多个字段,字段之间用逗号隔开
updatetb_user set uname='kusy';--更新表中的所有用户名
------------修改表的结构------
select* from tb_user;
alter tabletb_user add usex varchar(4); --添加一个字段
alter table tb_user dropcolumn usex; --删除一列
alter table tb_user altercolumn upass varchar(32);[W用3] --修改表的字段的类型
insertinto tb_user(uname,upass)values('999','3333'); --upass的类型已经变成了varchar类型
添加外键
--------------------------------------------------
--创建两张表
--教室表
createtable classname(--外键表
cid int,--设置为主键不为空
cname varchar(22)
);
droptable tb_student;
--学生表
createtable tb_student(--主键表
sid int primary key[W用4] not null identity[W用5] (1,1),--自增长为
sname varchar(32),
stel int
);
--添加外键
--alter table外键表名add constraint外键约束名foreign key (外键表的字段) references表名(主键表的字段)
alter table classname addconstraint f_u_c foreign key (cid) references tb_student (sid);[W用6]
--删除约束
altertable classname drop f_u_c;--删除某张表的约束
第二天
--复习昨天的内容
dropdatabase db4;
createdatabase db2;
usedb2;
createdatabase db3
on(
name='db3',
filename='C:\Program Files\Microsoft SQLServer\MSSQL.1\MSSQL\Data\db3.mdf',
size=5,
maxsize=10,
filegrowth=3
)
logon(
name='db3_log',
filename='C:\Program Files\Microsoft SQLServer\MSSQL.1\MSSQL\Data\db3.ldf',
size=5,
maxsize=10,
filegrowth=3
);
usedb3;
createtable tb_class--外键表
(
cid int primary key not null,
cname varchar(32)
);
createtable tb_stu--主键表
(
sidint primary key not null identity (1001,1),
snamevarchar(32),
stlint
);
insertinto tb_stu values('kusy',123);
select* from tb_stu;
selectdistinct sname,stl from tb_stu;
--删除数据
deletefrom tb_stu where sid=1001;
--更新数据
updatetb_stu set sname='roy' where sid=1002;
updatetb_stu set sname='战神七';
--查找数据
select* from tb_class;
select* from tb_stu;
altertable tb_class drop f_k;
truncatetable tb_class;
truncatetable tb_stu;
--添加外键
--altertable表名
--addconstraint约束名foreign key (外键表的ID) references主键表(主键表的ID)
altertable tb_class
addconstraint f_K foreign key (cid)
referencestb_stu (sid);
两张表关联后的增删除查改
---------------两张表关联之后的增删改查--------------
--对于两张表设置了主外键关联(两张表关联之后的增删改查)---
select* from tb_stu;
select* from tb_class;
--涉及到数据添加的时候
--先添加主键表的数据,如果主键表没有外键表所需要的外键值,也就是外键表在进行
--操作的时候,ID没有在主键表中存在会报约束的错误
insertinto tb_stu(sname,stl) values('kusy',123);--主键表
insertinto tb_class(cid,cname) values(1003,'java1');--外键表
--涉及到数据更新操作的时候
--update表set字段=新值where条件中的id (也必须是主键表中存在的ID,这样才能保证数据的完整性)
updatetb_class set cname='嵌入式' wherecid=1002;
--删除先删除外键表的数据再删除主键表的数据
--deletefrom表名where条件(尽可能唯一)
deletefrom tb_stu where sid=1001;--主键表
deletefrom tb_class where cid=1001;--外键表
createdatabase db1;--创建数据库db1
usedb1;--使用数据库db1
--创建表
createtable tb_user
(
uid int primary key not null identity(1,1),
uname varchar(32),
upass varchar(32)
);
--插入数据
insertinto tb_user values('abc','root');
insertinto tb_user values('Roy3','root');
insertinto tb_user(uname,upass)values('战神七','root');
--查询数据
select* from tb_user;
select * fromtb_user order by uid desc;--按id倒序查询
select * from tb_user orderby uid asc; --按id正序查询[W用7]
--count计数现在是汇总当前表的记录条数总共有多少条
selectcount(*)[W用8] as '记录条数' from tb_user;
-----区间查询------------------
--between3 and 5查询到之间的数据
select * fromtb_user where uid between 3 and 5;[W用9]
--满足两个条件的语句
select* from tb_user where uname='abc' and upass='root';
--满足一个条件的语句
select* from tb_user where uname='战神七' orupass='root';
--排除某个条件以外的数据
select* from tb_user where not uid=3;
select* from tb_user where not uname='abc';
--查询ID指点的几个数据
select* from tb_user where uid in(4,5,6,8);
模糊查询
--名字包含a的数据
select * fromtb_user where uname like '%a%';
select * from tb_user whereuname like 'a%'; --百分号带表N个字符
select * from tb_user whereuname like 'ab_'; --下划线代表一个字符[W用10]
--对数据进行分组查询同事按照分组的情况进行升序或者降序排列
selectuname from tb_user group by uname order by uname desc;
selectuid from tb_user group by uid order by uid asc;
--记录多少条
selectcount(*) as '总数' from tb_user;
--查询最大、最小的值
select max(uid)as 'ID最大的值' from tb_user;
select min(uid) as 'ID最小的值' from tb_user;[W用11]
--查询表里面的前两行数据
selecttop 2 * from tb_user;
selecttop 2 * from tb_user where uid not in
(selecttop 4 uid from tb_user);
备份数据库
backupdatabase db1 to disk='f:\db.dat' with format,name='db1';
--查看备份文件的内容
restorefilelistonly from disk='f:\db.dat';
dropdatabase db1;--删除数据库
--数据库的还原
restoredatabase db1 from disk='f:\db.dat' with move
'db1'to 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\db1.mdf',
move'db1_log' to 'C:\Program Files\Microsoft SQLServer\MSSQL.1\MSSQL\Data\db1.ldf';
createdatabase db5;
usedb5;
--创建两张表
createtable tb_stu --外键表
(
s_unm char(12) primary key,
s_name varchar(32),
s_cid int,
s_age int
);
createtable tb_class --主键表
(
c_id int primary key identity(1,1),
c_name varchar(32),
c_teacher varchar(32),
c_num int
);
droptable tb_stu;
--设置两张表的关系
--将tb_stu的s_cid设置成外键和tb_class表中的cid设置成主键进行关联
alter tabletb_stu add constraint f_s_c foreign key(s_cid) references tb_class(c_id);[W用12]
--添加数据先添加主键表
insertinto tb_class(c_name,c_teacher,c_num)values('计科班','12',48);
insertinto tb_class(c_name,c_teacher,c_num)values('计科班','12',49);
insertinto tb_class(c_name,c_teacher,c_num)values('计科班','12',55);
--查询数据
select* from tb_class;
select* from tb_stu;
--添加信息添加外键表
insertinto tb_stu values(18,'zhong',1,25);
insertinto tb_stu values(23,'77',2,22);
insertinto tb_stu(s_unm,s_name,s_cid,s_age) values(25,'xiaoming',3,4);
insertinto tb_stu values(24,'hao',1,23);
--查询所有的学生信息对应班级的信息两张表的联查
selects.s_unm,s.s_name,s.s_age,c.c_name,c.c_teacher,c.c_num
from tb_stu s,tb_class c --在这里c和s是别名
where s.s_cid=c.c_id; --这是两张表的关联所在[W用13]
--查询班级人数大于的班级
selectc_id from tb_class where c_num>48;
--查询和zhong在同一个班级的学生
selects_cid from tb_stu where s_name='zhong';--查找到zhong在哪个班级
select* from tb_stu where s_cid in(select s_cid from tb_stu where s_name='zhong');--根据班级再次查找到跟他同班的人
--查询12所在班级的学生的所有信息
selectc_id from tb_class where c_teacher='12';--查找12所交的班级
selects_name,s_unm,c_name
fromtb_stu,tb_class
wheretb_stu.s_cid=tb_class.c_id --学生要和班级是对应的
ands_cid in(select c_id from tb_class where c_teacher='12');
--查询77的老师
selects_cid from tb_stu where s_name='77';
selectc_teacher from tb_class where c_id in(select s_cid from tb_stu where s_name='77');
--班级号
selectc_id from tb_class where c_teacher in(
selectc_teacher from tb_class where c_id in(
selects_cid from tb_stu where s_name='77'));
--和77在同一个班级的指定的信息
selects_name,c_name from tb_stu,tb_class where c_id in(
selectc_id from tb_class where c_teacher in(
selectc_teacher from tb_class where c_id in(
selects_cid from tb_stu where s_name='77')))
ands_cid=c_id;
存储过程
--存储过程:存储过程类似于c语言里面的函数,用来执行任务或者是业务逻辑比较复杂的时候,可以带参数也可以返回结果
--存储过程可以包含数据操纵语句,变量,逻辑控制语句等
--存储过程的优点:执行的速度快2可以进行模块化设计3提高了安全性4减少了网络的流通量
--存储过程分为:自定义存储过程系统存储过程
--写一个sql的函数,完成一个功能,统计出性别为女的人数
createtablepeople
(
pid intprimary key not nullidentity(1,1),
pnamevarchar(32),
psex varchar(32),
ptel int,
pageint
);
insertintopeople values('小明','男',1,12);
insertintopeople values('小王','女',1,21);
insertintopeople values('张三','女',1,14);
insertintopeople values('小呆','男',1,15);
insertintopeople values('李四','女',1,23);
insertintopeople values('文章','女',1,27);
altertablepeople add page int;
truncatetablepeople;
droptablepeople;
--查询
select*from people;
--如果人数大于四打印“女生人数大于四”如果人数小于等于四则打印“女生人力资源不足”
declare
@numint--在declare的声明部分,完成变量的声明,所有的变量前都要加上@这个符号
begin
set@num=0
select@num=COUNT(*)frompeople where psex='女'[W用14]
if(@num>3)
begin
print'女生人数大于三'
end
else
begin
print'女生人力资源不足'
end
end
----------------常见的系统存储过程--------------------------------
--调用系统存储过程execute procedure
--显示所有的数据库列表
execsp_databases;
--显示数据库db1的详细信息,并且显示对应的数据文件和日志文件信息
--sp_helpdb如果没有指定数据库名,则表示显示所有的数据库信息
execsp_helpdb'db1';
--如果调用的存储过程需要多个参数,我们就用","好隔开
--给已经存在的数据库重新命名
execsp_renamedb'db2','db1';
--返回当前环境下用户可以访问的所有的表和视图
execsp_tables;
--返回指定表的字段的信息
execsp_columnspeople;
--返回当前状态下数据库中所有的表
execsp_help;
execsp_help'people';--指定了表的名称则返回相应表的详细信息
--查询指定表的所有约束信息
execsp_helpconstraint'people';
--为pname字段创建索引
createindexindex1 on people(pname);
--查询指定表的所有信息
execsp_helpindex'people';
--显示当前的可用的所有存储过程
execsp_stored_procedures;
--添加或者更改登录密码
execsp_password'sa','admin';
----------------自定义存储过程---------------------------
--自己定义存储过程:计算所有学生的平均年龄
--打印出平均年
--打印出最大年
--打印出最小年龄
--打印出年龄小于平均年龄的的所有学生
dropprocproc_print;
select*from people;
createprocproc_print
as
declare
@maxint,@minint,@avgint--定义的三个变量最大最小平均
begin
select@max=MAX(page)frompeople;
select@min=MIN(page)frompeople;
select@avg=AVG(page)frompeople;[W用15]
print'最大年龄:'+convert(varchar,@max)
print'最小年龄:'+convert(varchar,@min)
print'平均年龄:'+convert(varchar,@avg)
select*from people where page<@avg
end
go
--执行存储过程
execproc_print;
dropprocproc_print;
--------------------------------------------------
--创建一个带返回值得存储过程
createprocp_proc1
@avgintoutput--指定为输出的参数
as
select@avg=AVG(page)frompeople
go
--创建带有输出参数的存储过程
declare
@aaaint
begin
execp_proc1@aaaoutput--执行存储过程把结果打印出来
print'平均年龄是:'+convert(varchar,@aaa)
end;
--------------------------------------------
--创建带有两个输出参数的存储过程
createprocp_proc2
@maxintoutput,@minintoutput
as
select@max=MAX(page)frompeople
select@min=MIN(page)frompeople
go;
--调用带有两个输出参数的存储过程
declare
@aaaint,@bbbint
begin
execp_proc2@aaaoutput,@bbboutput
print'最大值:'+convert(varchar,@aaa)
print'最小值:'+convert(varchar,@bbb)
end
-------------------------------------------
--创建一个带有输入参数的存储过程
createprocp_proc3
@input_ageint--定义的变量为输出参数
as
select*from people where page<@input_age
go
--调用带有输入参数的存储过程直接执行存储过程
execp_proc320;
--另外一种调用方法
declare
@ageint
begin
set@age=20
execp_proc3@age--当我们这个变量是用来传递输入参数的是不需要input
end
---------------------------------------------------
--创建一个带有两个输入参数的存储过程
createprocp_proc4
@age1int,
@age2int
as
if(@age1>=@age2)
begin
select* frompeoplewhere page>@age2andpage<=@age1
end
else
begin
select* frompeoplewhere page>@age1andpage<=@age2
end
go
--直接执行调用带有两个输入参数的存储过程
exec p_proc410,20;
--创建带有两个输入参数和一个输出参数的存储过程
publicintadd(inta,intb){
intc=a+b;
returnc;
}
createprocp_add
@aint,
@cintoutput,
@bint
as
set@c=@a+@b
go
--调用带有两个输入参数和一个输出参数的存储过程
declare
@sumint
begin
execp_add9,@sumoutput,8
print'计算的结果:'+convert(varchar,@sum)
end
----------------------------------------------
--创建一个存储过程:输入页面的长度和页码,可以查询到相应的数据
--pagesizepagenum
createprocp_splitpage
@pagesizeint,--每一页有多少条数据
@pagenumint--总的记录条数
as
declare
@countint,--总记录数据条数
@numint--总页数
select@count=count(*)frompeople
if(@count%@pagesize>0)--总的页数
begin
set @num=@count/@pagesize+1
end
else
begin
set @num=@count/@pagesize
end
--如果用户输入的页码小于则默认显示第一页
if(@pagenum<1)
begin
set @pagenum=1
end
--如果用户输入的页码大于最大页则默认显示最后一页
if(@pagenum>@num)
begin
set @pagenum=@num
end
selecttop(@pagesize)*frompeople where pid notin(
select(@pagesize*(@pagenum-1))pidfrom people)
go
execp_splitpage20,186;
selecttop(10)*frompeople where pid notin
(select(20*(20-1))pidfrom people);
商品销售
商品销售数据库
Article(商品号(aid)char(4),商品名(aname) char(16),单价(aprice) Numeric(8,2),库存量(aquantity) int)
Customer(顾客号(cno) char (4),顾客名(cname) char (8),性别(csex) char(2),年龄(cage) int)
OrderItem(顾客号(cno) char(4),商品号(aid) char(4),数量(oquantity) int, 日期(odate) date)
1 查询定购商品号为‘1001’或‘1002’的顾客号;
2 查询没定购商品的顾客号和顾客名。
3 查询定购商品号‘1001’商品数量最多的顾客号和顾客名。
4 查询男顾客的人数和平均年龄。
5 查询至少订购一种商品的顾客数。
6 查询顾客张三订购商品的总数量及每次购买最多数量和最少数量之差。
7 查询年龄在30至40岁的顾客所购买的商品名及商品单价。
8 查询购买的商品的单价至少有一次高于或等于1000元的顾客号和顾客名。
createdatabaseshangping;
use shangping;
createtableArticle
(
aidintprimary key not nullidentity(1001,1),
anamechar(16),
apriceNumeric(8,2),--Numeric(8,2)指字段是数字型,长度为8,小数为两位[W用19]
aquantityint
);
createtableCustomer
(
cnointprimary key identity(1,1),
cnamechar(8),
csexchar(2)check(csexin('男','女'))default'女',
cageint
);
createtableOrderItem
(
cnoint,
aidint,
oquantityint,
odatedate
);
--三张表关联
altertableOrderItem add constraint o_aforeignkey(aid)referencesArticle(aid);
altertableOrderItem add constraint o_cforeignkey(cno)referencesCustomer(cno);[W用20]
--1添加商品
createprocp_addArticle
@namechar(16),
@priceNumeric(8,2),
@quantityint
as
declare
@mint,--查找数据库中是否有该商品并记录
@nint--该商品的库存量
select@m=count(*)fromArticle where aname=@name
select@n=aquantityfromArticle where aname=@name
if(@m=0)
begin
insertinto Articlevalues(@name,@price,@quantity);
print'添加商品成功!'
end
else
begin
updateArticle setaquantity=@n+@quantitywhereaname=@name
print'更新了商品的库存量!'
end
go
execp_addArticle'玩具小熊',23.00,20;
execp_addArticle'宏基笔记本',1000.00,10;
execp_addArticle'平板电脑',2000.00,50;
execp_addArticle'123',12.00,30;
select*from Article;
dropprocp_addArticle;
--2添加顾客
createprocp_addCustomer
@namechar(8),
@sexchar(2),
@ageint
as
begin
insertintoCustomer values(@name,@sex,@age)
print'添加数据成功!'
end
go
execp_addCustomer'司空见惯','男',23;
execp_addCustomer'欧阳菲菲','女',20;
execp_addCustomer'刘亦菲','女',24;
execp_addCustomer'张三','男',25;
execp_addCustomer'李莫愁','女',37;
execp_addCustomer'李静','男',32;
execp_addCustomer'马伊琍','女',39;
select*from Customer;
--3订购商品
createprocp_OrderItem
@cnoint,
@anamechar(16),
@quantityint
as
declare
@aidint,--商品id
@xint,--查看是否订购过
@yint,--订购过多少
@jint,--查看是否有这个商品
@mint,--查看商品库存是否足够
@nint--订购后商品的库存量
select@aid=aidfromArticle where aname=@aname
select@x=count(*)fromOrderItem where cno=@cnoandaid=@aid
select@y=oquantityfromOrderItem where cno=@cnoandaid=@aid
select@j=count(*)fromArticle where aname=@aname
select@m=aquantityfromArticle where aname=@aname
if(@j=0)--没有这个商品
begin
print'没有该商品!'
end
else
begin
if(@m<@quantity)
begin
print'商品库存不足,无法完成订购'
end
else
begin
if(@x=0)
begin
insert into OrderItemvalues(@cno,@aid,@quantity,getdate())
print '订购商品成功!'
end
else
begin
update OrderItem set oquantity=@quantity+@ywherecno=@cnoandaid=@aid
update Article setaquantity=@m-@quantitywhereaid=@aid
print '更新了商品库存量和订购商品的数量!'
end
end
end
go
execp_OrderItem2,'玩具小熊',2;
execp_OrderItem3,'宏基笔记本',1;
execp_OrderItem4,'玩具小熊',10;
execp_OrderItem4,'宏基笔记本',1;
execp_OrderItem4,'平板电脑',5;
execp_OrderItem5,'平板电脑',2;
execp_OrderItem6,'宏基笔记本',3;
select*from OrderItem;
select*from Article;
select*from Customer;
--4根据定购商品号来查询顾客号
createprocp_find1
@aidint
as
declare
@xint--查看是否订购了该商品
select@x=count(*)fromOrderItem where aid=@aid
if(@x=0)
begin
print'该商品没有顾客订购!'
end
else
begin
selectcno fromOrderItemwhere aid=@aid
end
go
execp_find11;
execp_find11002;
--5查询没有订购商品的顾客号和顾客名
selectcno,cnamefromCustomer where
cno not in(selectcnofrom OrderItem);
--6查询定购商品号‘’商品数量最多的顾客号和顾客名
createprocp_find2
@aidint
as
declare
@maxint,
@cnoint,
@mint
select@m=count(*)fromOrderItem where aid=@aid
select@max=max(oquantity)fromOrderItem where aid=@aid
select@cno=cnofromOrderItem where aid=@aidandoquantity=@max
if(@m=0)
begin
print'没有人订购该商品!'
end
else
begin
selectcno,cnamefromCustomer where cno=@cno
end
go
dropprocp_find2;
execp_find22;
--7查询男顾客的人数和平均年龄
createprocp_print1
as
declare
@numint,
@avgint
select@num=count(*)fromCustomer where csex='男'
select@avg=avg(cage)fromCustomer
begin
print'男顾客人数:'+convert(varchar,@num)
print'男顾客平均年龄:'+convert(varchar,@avg)
end
go
dropprocp_print1;
execp_print1;
--8查询至少订购了一种商品的顾客数
createprocp_Orderone
as
declare
@numint
select@num=count(*)fromOrderItem where cno in(selectcnofrom OrderItem)
begin
print'至少订购了一种商品的顾客数:'+convert(varchar,@num)
end
go
execp_Orderone;
--9查询顾客张三订购商品的总数量及每次购买最多数量和最少数量之差
createprocp_zhansan
as
declare
@countint,
@maxint,
@minint,
@cnoint
select@cno=cnofromCustomer where cname='张三'
select@count=sum(oquantity)fromOrderItem where cno=@cno
select@max=max(oquantity)fromOrderItem where cno=@cno
select@min=min(oquantity)fromOrderItem where cno=@cno
begin
print'张三订购商品的总数是:'+convert(varchar,@count)[W用21]
print'购买最多数量和最少数量的差为:'+convert(varchar,@max-@min)
end
go
execp_zhansan;
--10查找年龄在至岁的顾客所购买的商品名及商品单价
selectaname,apricefromArticle where aid in(
selectaidfrom OrderItem where cnoin
(selectcnofrom Customer where
cage>=30andcage<=40));
--11查询购买的商品的单价至少有一次高于或等于元的顾客号和顾客名
selectcno,cnamefromCustomer where cno in(
selectcnofrom OrderItem where aidin((
selectaidfrom Article where aprice>=1000)));
select*from Article;
select*from Customer;
select*from OrderItem;
droptableOrderItem;
droptableArticle;
drop table Customer;