2014-11-27 字符串函数和查询

一、字符串函数 String Functions

ASCII:返回字符串最左侧字母的ASCII码

          对应的为char,将ASCII码转化为字符

charindex:在一个表达式中搜索另一个表达式,并返回其位置

例:print charindex('de','abcdefg') ---其结果为4,逗号前为被查找内容,后为查找的位置,结果为第几位

soundex:将一个字符串转化为一个4位的编码(1位字母+3位数字)

difference:比较两个字符串的soundex值重复的有几位

space:打空格  例:select space(10)--打10个空格

left:返回字符串中从左往右指定个数的字符

right:返回字符串中从右往左指定个数的字符,但输出结果时从左往右输出

例:select right ('abcdefgh',3)---其结果为fgh

len:返回字符串的长度(不含句尾的空格)

lower:大写转为小些

upper:小些转为大写

ltrim:去除字符串前空格

rtrim:去除字符串后空格

partindex:用法与charindex一致。但partindex必须加通配符“%%”

replace:替换。

例:select replace ('abcdefahhhh','ab','@#')---其结果为@#cdefahhhh,第一个为目标字符串,第二个为需要替换的字符,第三个为替换为xx

replicate:复制。

例:select replicate ('ab',3)---其结果为‘ababab’,3为复制的次数

reverse:返回字符串的逆序

STR:将float类型截取之后转换为字符串型

例:print str (12.123456,5,2)--其结果为12.12,第一个数为需要操作的数,第二个为需要保留几位(包含标点空格),第三个为保留小数点后几位

stuff:print stuff(‘abc123defgh’,4,3,‘abc’)--其结果为‘abcabcdefgh’,先删除后替换

substring:截取字符串

例:select substring(‘abcdef’,3,1)---其结果为c

常用函数:

substring,reverse,replace,ltrim,rtrim,lower,upper,len,left,right,charindex

二、类型转换函数

cast:select cast (‘123’ as int)---把123转换为int型

convert:select convert(int,‘123’)

三、连接查询

1.join……on……

例:select sno,score.cno,cname,degree from score join course on score.cno=course.cno

                                               后面可以继续接条件 join student on student.sno=score.sno

join 前可以加修饰词条件语,如 left join,right join(以前一个或后一个表为基准)

2.两表直接拼接,后跟where建立条件

例:select score.sco,sname,sco,degree from score,course where score.con=course.cno

3.纵向连接:将两个表里同一列的连接起来

例:select sname,ssex from student  uinon  select tname,tsex from teacher

posted @ 2014-11-27 19:56  雪山飞驴  阅读(205)  评论(0编辑  收藏  举报