SqlServer基础操作
1.创建数据库
if DB_ID('name') is null
create database class;
go
2.删除数据库
if DB_ID('name') is not null
drop database class;
go
3.创建表
create table [dbo].[student](
[id] [int] identity(1,1),
[name] [varchar](50) not null,
[course] [varchar](50) not null,
[score] [int] not null
)ON [PRIMARY]
go
4.删除表
-- sysobjects是数据库中的表,表的内容是数据库所有表的信息
if exists (select * from sysobjects where name='student')
drop table student
go
数据基本CRUD
1.插入
INSERT INTO 表名(表列1,表列2) values(标列1数据,表列2数据)
2.修改
-- 修改值
update 表名 set 列名1 = 值1 where 列名2 = 值2
3.删除
delete from 表名 where 条件列 = 条件值
go
4.查询
-- 查询表中的某列
select 列名1,列名2,列名3 from 表名
-- 查询表中的所有列
select * from 表名
1.别名查询,查询出的结果拼接
-- top(10) 表示查询前十个数据
select top(10) 列名 as 别名,列名 as 别名 from 表名
2.条件查询
select * from 表名 where 列名 = 列值
3.范围查询
-- 取值范围
select * from 表名 where id > 5 and id < 20
-- 从什么到什么,前小后大
select * from 表名 where id between 4 and 20
4.null判断
select * from 表名 where 列名 is null
5.查询前多少行/按比例查询结果
-- 查询前三行
select top 3 * from 表名
-- 查询前百分之20
select top(20) percent * from 表名
6.case when 判断
select *,case when 条件1 then 条件1等于的值
when 条件2 then 条件2等于的值
else 以上条件都不满足等于的值
end as 别名
from 表名 order by course asc
7.in查询
-- in就是列值等于()里的就显现出来
select * from 表名 where 列名 in (列值1,列值2,列值3)
8.like查询(模糊查询)
-- 此方法需要与通配符一起使用
select * from 表名 where 列名 like '%嘉%'
9.with关键字查询
此查询是把查询出来的结果整理出一个表中,然后可以通过这个新的表再次进行查询
with 新表名 as (select * from 原表名 where)
select * from 新表名
10.子查询/exists关键字查询
-- 子查询
-- 就是用一个表所查出的值,作为关键字再去查另一个表
select * from 表名1 where 列 in(select 列 from 表名 where 条件)
-- exists关键字
-- 个人理解exists()里面有值(true)则第一查询就有结果,如果没有值(false)第一个查询就不查询
select * from 表名1 where exists (select * from 表名 where 条件)
-- 如果两个表做关联,两次查询都一样的,exists就会把后一个查询的结果返回给上一个查询的结果
select * from 表名1 t1 where exists (select * from 表名2 t2 where t1.id = t2.id and 条件)
11.复制新表/表数据复制
-- 复制新表
select * into 新表 from 被复制的表
-- 表数据复制
insert 新表 select 所复制的数据列 from 被复制的表
12.distinct同一列去掉重复
select distinct 列名,列名,列名 from 表名
13.排序
升序asc,降序desc 可多列排序,优先级从左往右
select * from 表名 order by 列名,列名 desc
14.聚合查询分组
select 列名,sum(score) 别名 from 表名 group by 按照哪一列汇总(列名)