1.新建数据库
-- 1.1 新建数据库
create database 库名
on(
--指定数据库名
name ='库名',
--指定路径以及文件后缀
filename ='C:\库名.mdf',
--指定数据库初始容量
size =3MB,
--指定数据库最大容量
maxsize =50MB,
--指定数据库自动增长容量
filegrowth =1MB
)
-- 1.2 新建数据库日志
log on(
--指定数据库名
name ='库名_log',
--指定路径以及文件后缀
filename ='C:\库名_log.mdf',
--指定数据库初始容量
size =3MB,
--指定数据库最大容量
maxsize =50MB,
--指定数据库自动增长容量
filegrowth =10%
)
--1.3 删除数据库
drop database 库名
2.新建数据表
--2.1 新建数据表
create table 表名
(
--primary key主键
--identity自动增长
列名 int primary key identity(1,1),
--列名,数据类型,为不为空
--not null不为空
--foreign key 外键
列名 int not null foreign key references 表名(列名),
--列名,数据类型,为不为空
--check约束
列名 smallint check(列名>=0 and 列名<=100)
)
--2.2 删除数据表
drop table 表名
3.增删改查
--3.1插入数据
insert into 表名(列名,列名...)values('',''...) ;
--3.2修改全部数据
update 表名 set 列名=' ' ;
--3.3修改指定数据
update 表名 set 列名=' 'where 列名= ;
--3.4查询数据
select * from 表名 ;
--3.5删除数据
delete from 表名 ;
--3.6 删除指定的数据
delete from 表名 where 列名=' ' ;
4.查询数据
--4.1查询全部的行和列
select * from<表名>
--4.2 查询部分行
select<列名>from<表名>where<条件>
--4.3 使用AS来命名直接查询结果列
select as<列名>,as<列名>from<表名>where<条件>
--4.4 使用=来命名列
select '列名'=<原始列名>+':'+<原始列>from<表名>
--4.5 限制固定行数
select top<行数><列名>from<表名>where<条件>
--4.6 返回百分之多少行
select top<百分之数字><列名>from<表名>where<条件>
--4.7 升序排序
select*from<表名>order by<列名>
--4.8 降序排序
select*from<表名>order by<列名>desc
--4.9 多列排序
select*from<表名>order by<列名>,<列名>
--4.10 查询不同的
select distinct<>from<表名>
--4.11 模糊查询-like
select<列名>from<表名>where<条件>like' % % '
--4.12模糊查询-is null(把某一字段中内容为空的记录查询出来)
select<列名>from<表名>where<条件>is null
--4.13 模糊查询-between(把某一字段中内容在特定的范围内的记录查询出来)
select<列名>from<表名>where<条件>between<条件>
--4.14 模糊查询-in(把某一字段中内容与所列的查询内容列表匹配的记录查询出来)
select<列名>from<表名>where<条件>in<条件>
--4.15 count计算个数
select count (列名),from<表名>where<条件>
--4.16 sum计算总和
select sum (列名),from<表名>where<条件>
--4.17 avg计算平均值
select avg (列名),from<表名>where<条件>
--4.18 max计算最大值
select max (列名),from<表名>where<条件>
--4.19 min计算最小值
select min (列名),from<表名>where<条件>
--4.20 分组查询-group by
select<列名>,avg(表名)as 课程平均成绩from<表名>group by <列名>
--4.21 分组查询-having
select<列名>,avg(表名)as 课程平均成绩from<表名>group by <列名>having avg(表名)>=60
5.连接查询
--5.1 子查询--in
select * from <表名> where <列名> in(select distinct <列名> from <表名>)
--5.2 子查询--exists关键字--not exists关键字
select * from <表名> where exists(select * from <表名> where <表名>=<列名>)
select * from <表名> where not exists(select * from <表名> where <表名>=<列名>)
--5.3 内连接--1.确定列--2.确定表--确定条件--内连接关键字(inner join)
select <列名>,<列名>,<列名> from <主表名> inner join <子表名> on <子列名>=<主列名>
--5.4 外连接--左外连接(left join)--右外连接(right join)--完整外连接(full join)
select <列名>,<列名>,<列名> from <主表名> <连接名称关键字> <子表名> on <子列名>=<主列名>