SQL 操作字符串

SQL操作字符串相对来说比较难一点,现在总结几个常用的SQL 对字符串的操作:

declare @dd nvarchar(12) set @dd='2015-03-13' print @dd declare @cc nvarchar(12)

--替换指定字符 set @cc=replace(cast(@dd as nvarchar(12)),'-','')

--截取替换字符串:stuff('sourceStr',startIndex,length,'destinateStr') select stuff('Welcome to china!',5,4,'good') --result:Welcgoodto china!

--根据索引与长度获取子字符串:substring('sourceStr',startIndex,length) select substring('Welcome to china!',2,8) --result:elcome t

--去除字符串的(左)空格:ltrim(' sourceString') select ltrim(' Welcome to china!') --result:Welcome to china!

--去除右边的空格:rtrim('Welcome to china! ') select rtrim('Welcome to china! ') --result:Welcome to china!

--去除左右边的空格:lrtrim(' Welcome to china! ')

--指定字符代替字符串中的null:isnull('destinationChar',null) select isnull('a',null) --result:a

--获取字符串长度:len('Welcome!') select len('Welcome--') --result:9

--获取字符串的左右(多个)字符 /也可以获取前后几个字符 select left('welcome,girls',4)--result:welc select right('welcome,girls',4) --result:irls select right('welcome,girls',(len('welcome,girls')-3)) --result:come,girls

--获取字符在字符串中的位置:charIndex('char','sourceStr') select charindex('l','welcome to china~~') --result:3

--大小写转化lower/upper('sourceStr') select lower('WELCOME TO CHINA!') --result:welcome to china!

--复制字符串replicate('str',times) select REPLICATE('Welcome to china!',3) --result:Welcome to china!Welcome to china!Welcome to china!

--反转字符串 reverse('welcome') select reverse('welcome to china!') --result:!anihc ot emoclew

 

若有不足的,大家一起补充学习!

posted @ 2015-03-23 14:05  肖恩部落  阅读(514)  评论(0编辑  收藏  举报