1.什么是查询?
客户端程序 查询请求到 SQL Server 把查询结果集 交到临时表
查询产生一个虚拟表,看到的是表形式显示的结果,但结果并不正真存储,每次执行查询只是从数据表中提取数据,并按照表的形式显示出来。
2.查询语法
select 列名
from 表名
where 查询条件
order by 列名 (升序ASC(默认),DESC降序)
eg:select Name from Student
where sex=‘女‘
order by Score
3.查询全部的列和行
select * from Student (* 尽量少使用,减低查询效率)
4.查询部分
select Name,sex from Student
5.查询部分行和列,带条件
select sex,Email from Student where StudentName=‘李四‘
6.使用AS命令
(1)select StudentName as 学生姓名,sex as 性别 from Student
(2)select StudentName+‘--‘+sex as 姓名和性别 from Student
7.使用等于命令
select 姓名和性别=StudentName+‘--‘+sex from Student
注意:
(1)+连接的数据类型必须兼容
(2)如果+连接字符数据,结果为字符串数据的连接
(3) 如果+连接数值型数据,结果为数值的和
8.查询空行
select name from Student where Emai is null
9.查询不为空
select SubjectName from Subject where ClassHour is null or ClassHour !=‘‘
10.使用常量列
select 姓名=name,‘张三‘ as 学生姓名 from Student
11.限制行数
限制固定函数
select Top 5 StudentName,sex from Student
按百分数返回
select Top 5 percent StudentName,sex from Student where sex=‘女‘(百分数只能在0—100之间)
12.查询单列排序
升序排列
select StudentNo as 学生编号,(StudentResult*0.5)as 综合成绩
order by StudentResult (默认不写就是升序)
降序排列
select StudentNo as 学生编号,(StudentResult*0.5)as 综合成绩
order by StudentResult desc
13.查询多列排序(用逗号隔开)
select StudentId as 学生编号,score as 成绩
from Scores
order by Score,StudentId(或者是desc降序)
注意:
多行排序,先按照第一个进行升序/降序排序
14.字符串函数
(1)charindex:寻找字符串在下一个指定字符串的起始位置(sql起始位置从1开始)找不到,返回0
eg:select charindex(‘JBSN‘,‘My jbsn‘,1)
解释:(‘要查询的字符串‘,‘被查询的字符串‘,从被查询字符串哪里开始查找)
返回:4
(2)len:字符串长度
eg:select len(‘SQL Server课程‘)
返回:12
(3)upper:转为大写
eg:select upper(‘zhangsan‘)
返回:ZHANGSAN
(4)ltrim:清除左边空格
eg:select ltrim(‘ 李四‘)
返回: 李四
(5)rtrim:清除右边空格
eg:select rtrim(‘李四 ‘)
返回: 李四
(6)right:从字符串右边返回指定字符
eg:select right(‘买卖提.土尔松‘,3)
解释: 3是返回字符串个数
返回: 土尔松
(7)left:从字符串左边返回指定字符
eg:select left(‘买卖提.土尔松‘,3)
解释: 3是返回字符串个数
返回: 买卖提
(8)replace:替换字符(只适用于部分字符,而update用于整行替换)
eg:select replace(‘莫乐可切‘,‘可‘,‘兰‘)
解释:(‘原字符‘,‘找到可‘,‘替换成兰‘)
返回:莫乐兰切
(9)stuff:在zifuchuanz,删除指定长度字符,在该位置插入新字符
eg:select stuff(‘ABCDEFG‘,2,3‘我的音乐‘)
解释:(‘原字符‘,从哪里开始删除,插入几个字符,‘插入新字符‘)
返回: A我的音乐EFG
原文:https://www.cnblogs.com/unique1/p/12707236.html