数据查询和管理

  对数据表的插入、更新、删除操作   

--数据查询和管理
--取消重复元组distinct
select distinct 民族 from 学生信息
go
--查询前几列数据
select top 6 * from 学生信息
select top 6 学号,姓名,民族 from 学生信息
go
--查询计算列
select 教师编号 as 'sno',姓名 as 'sname',2015-年龄 as 'sbrisday' from 教师信息
go
--使用别名查询,在列表中的名称,可使用的方法:空格,as,=,别名用单引号
select 教师编号 'tno',姓名 'tname' from 教师信息
select 'tno'=教师编号,'tname'=姓名 from 教师信息--顺序不能颠倒
go

--限定查询条件
--比较运算符>,<,>=,<=,<>,=,!=
select 姓名,年龄 from 教师信息 where 年龄>30
--范围运算符
select 姓名,出生日期 from 学生信息 where 出生日期 not between '1987-01-01' and '1992-01-01'
select 姓名,出生日期 from 学生信息 where 出生日期 between '1987-01-01' and '1992-01-01'
--逻辑运算符and,or
select 姓名,性别,民族 from 学生信息 where 性别='女' and 民族 like '汉%'
--字符匹配like,not like,=,!=;通配符'_','%'
--列表运算符in ,not in
select 学号,姓名,性别,所属班级 from 学生信息 where 所属班级 in(20050101,20050102)
go
--未知值
select 家庭住址 from 学生信息 where 家庭住址 is not null

--规范化查询
--排序查询asc,desc
select 学生编号,课程编号,分数 from 成绩信息 order by 分数 asc
go
--分组查询 group by...having....;where与having的区别,having可以加统计函数,而where没有
select 所属班级,count(学号) as 班级总人数 from 学生信息 group by 所属班级 having count(学号)>1
select min(年龄) as 最大年龄 from 教师信息 where 性别='女'
go

--将一个表中的数据插入到另一个表中
create table 新考试安排
(exam_no nchar(10) not null primary key,
exam_type nvarchar(50),
exam_date date)
go
insert into 新考试安排(exam_no,exam_type,exam_date)
select 考试编号,考试类型,考试时间 from 考试安排
select * from 新考试安排
go
--使用where子句来限定插入条件
create table 新学生信息
(st_no nvarchar(50) not null primary key,
st_name nchar(10) not null,
st_sex nchar(10) not null)
go
insert into 新学生信息(st_no,st_name,st_sex)
select 学号,姓名,性别 from 学生信息 where 性别='男'
go
select * from 新学生信息
go

--将查询结果集插入一个新表中select...into....,插入一个临时表中
select 班级编号,班级名,班级人数 into #班级基本信息 from 班级信息
select * from #班级基本信息
go
--更新数据
--根据表中数据更新行
update 班级信息 set 班级人数=班级人数+10 where 班级人数<20
select * from 班级信息
--根据其他表更新行
select 成绩信息.分数,课程信息.课程编号 from 成绩信息,课程信息 where 课程信息.课程编号='1'and 成绩信息.课程编号=课程信息.课程编号
go
update 成绩信息
set 分数='0'
where '1'=(select 课程编号 from 课程信息 where 成绩信息.课程编号=课程信息.课程编号)
go
--使用top表达式

      后续

原文地址:https://www.cnblogs.com/fffywfn/p/4204158.html