SQLSERVER字符串处理函数
sqlserver提供了一系列字符串处理函数:substring、left、right、len、charindex、patindex、replace、replicate、stuff、upper、lower、rtrim、ltrim等函数。
substring(string,strat,length) eg:? select? substring(‘abcde‘,1,3)返回子字符串‘abc‘ ???????????????????? ?select? substring(‘abcde‘,8)返回字符串‘abcde‘(如果length长度大于字符串长度,则返回原字符串)
left(sting,n)??????????? /????????????? right(string,n) eg:? select? left(‘abcde‘,3)返回字符串‘abc‘ ????????????????????? select? right(‘abcde‘,3)返回字符串‘cde‘
len(string)??????????? /????????????????datalength(string) eg:? select? len(‘and‘)返回字符数3 ?????? select? datalength(N‘abc‘)返回字节数6 ?????? select len(‘? abc?? ‘)返回5,无论有多少个连续空格,均计算一次 注:普通字符,字符串的字符数和字节数是一致的,这是因为一个字符只占一个字节的存储空间 ????????????? Unicode字符,字符串的字符数和字节数是不一致的,一个字符占用两个字节的空间,故字符数是字节数的一半 ?
charindex(substring,string[,start_pos]),可以选择性的指定搜索的起始位置,即对start_pos赋值,未对其赋值则从第一个字符开始搜索 eg:? select? charindex(‘m‘,‘abnmdemf‘,5)返回7 默认情况下,sqlserver对大小写是不敏感的,但是当设置了对大小写敏感COLLATE Latin1_General_CS_AS时(patindex函数同样适用): eg:? select? charindex‘test‘,‘this Test is Test‘ COLLATE Latin1_General_CS_AS)返回0 ?????? select? charindex‘test‘,‘this Test is Test‘ COLLATE Latin1_General_CI_AS)返回6
patindex(pattern,string) eg:? select patindex(‘%[0-9]%‘,‘abcd123efgh‘)返回5,查询数字0-9中任一数字在字符串‘abcd123efgh‘首次出现的位置,%表示数字前可以匹配任意长度的字符,包括空字符
replace(string,substring1,substring2)将substring1替换为substring2 eg:? select replace( ‘l-a 2-b‘,? ‘-‘,? ‘:‘)返回结果为‘1:a 2:b‘
replicate(string,n) eg:? select? replicate(‘abc‘,3)返回‘abcabcabc‘
stuff(string,pos,delete_length,insertstring) eg:? select? stuff(‘xyz‘,2,‘abc‘)返回‘xabcz‘
upper(string)????????? /???????? lower(string)
rtrim(string)?????????? /??????????ltrim(string) eg:? select? rtrim(ltrim(‘? abc?? ‘)) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |