您的位置:首页 > 数据库

T-SQL查询基础

2015-11-04 14:26 453 查看
今天来带大家了解下在sql server 中的查询机制

使用select语句进行查询

1.查询所有的数据行和列

select  *  from student


2.查询部分行和列

select scode,sname,saddress
from * student
where saddress='北京'


3.在查询中使用列的别名

select scode as 学生编号,sname as 姓名 ,saddress as 地址
from student
where saddress<>'北京'


4.查询空值

select sname from student
where semail is null


5.在查询中使用常量

select 姓名=sname ,地址=saddress,'汉族' as 民族
from student


6.查询返回限制的函数

select top 5 sname, saddress
from student
where Ssex=0


查询排序

如何使用order by

如果要按照一定顺序排列查询语句选中的行,则需要使用order by 字句,并且排序可以是升序(asc)可以是降序(desc),

eg:   将学生成绩按照升序排列

select studentID as 学生编号, CourseID as 课程ID,Score as 成绩

from Score

where Score >60

order by Score,CourseID


在查询中使用函数

1.字符串函数

函数名称:
1.CharIndex('str1','str2',index)//位置从开始
--第一个参数:要查询的字符串
--第二个参数:在哪个字符串中搜索
--第三个参数:从str2的第几个字母开始搜索
--注意点:如果在str2中没有找到str1,那么返回
eg:
SELECT CHARINDEX('JBNS','My Jbns Course')
2.len():获取小括号中字符串的长度,空格也算一个字符长度
eg:
SELECT LEN('SQL Server课程')
3.upper():将括号中出现的英文全部转换成大写
eg:
select upper('i can speak english.你能吗?')
select lower('I HAVE A DREAM')
4.LTrim():清除括号中内容左边的空格(left:right)
eg:
select rtrim('         生活不是林黛玉,      ')
5.既想移除左边空格,也想移除右边空格
eg:
select rtrim(ltrim('         生活不是林黛玉,      '))
select ltrim(rtrim('   你还好吧!   '))
6.思路灵活
eg:
select len(rtrim('今年奇怪了,北京没下雪,去去去    '))
7.substring('字符串',截取的位置,截取的长度)
eg:
select substring('我是中国人,我爱自己伟大的祖国,真的',6,1)
8.right():从字符串(左)右边返回指定类型的字符
eg:
select left('大家今天好像都没有交日记本,我去',3)
select right('大家今天好像都没有交日记本,我去',2)
9.replace('str1','要替换的字符','目标字符'):
eg:
select replace('张海迪,残疾人,虽然手不残疾,但是X残疾','残                疾','好')
10.stuff('字符串',删除的起始位置,删除的长度,'插入的字符串')
eg:
select stuff('我爱你中国,我爱你故乡',4,2,'北京')


2.日期函数

1.getdate():获取当前日期和时间
eg:
select getdate()
2.dateadd(按年/月/日添加,增量,时间)
eg:
select dateadd(yy,100,'2014-8-6')
select dateadd(year,-20,getdate())
3.datediff(按年/月/日求差,小时间,大时间)
eg:
select datediff(year,'1998-01-01',getdate())
4.datename:获取某个日期是星期几
eg:
select datename(dw,'2014-08-06')
5.datepart(mm,日期):获取指定日期对应的年/月/日部分
eg:
select datepart(yy,getdate())
通过该方式也可以获取当天是周几
eg:
select datepart(dw,getdate())


3.数学函数

1.rand():产生一个到之间的随机数
eg:
select right(rand(),4)
2..abs:取绝对值
eg:
select abs(-10)
select abs(10)非负数
3.ceiling:天花板,你要看天花板,抬头,向上取整
eg:
select ceiling(1.999991)
4.floor:向下取整
eg:
select floor(1.999999)
select ceiling(1.000000000000001)
select floor(2.999999999999999)
5.power(5,2)求幂值
eg:
select power(4,4)
select 1*2/3+5-56+100-5/100
select power(2,3)
6.round:将一个数字四舍五入到指定精度
eg:
select round(42.564,1)
7.sign:如果括号中写的是一个正数,返回,如果是负数,返回-1
eg:
--如果是返回
select sign(20)
select sign(0)
8.sqrt()开平方
eg:
select sqrt(9)


4.常用的系统函数

convert:(用来转换数据类型)
eg:
select convert (varchar(5),12345)
返回:字符串'12345'


ok 精彩的代码分析时间就到这里,请持续关注哦!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: