sqlserver 截取特定字符串

好久没写技术博客了。

最近遇到用sql语句截取字符串的问题,例如字段值为某一格式为“A-B-C-D”,或者“A-B-C”

1、截取出第四段字符D,如果为四段式,则截取,否则返回空

说明:先判断有多少个“-”,然后分别处理

select 

case when LEN(teststring)-len(REPLACE( teststring ,'-',''))= 3 then

right( teststring ,charindex('-',reverse( teststring) )-1)

else '' end 

from dual

2、截取前三段字符A-B-C。

可根据上面的语句的提示完成

select

case when LEN(teststring)-len(REPLACE( teststring ,'-',''))= 3 then

SUBSTRING( teststring ,0,charindex(right( teststring ,charindex('-',reverse( teststring ) )-1), teststring )-1) 

else  teststring  end

from dual

猜你喜欢

转载自degree38.iteye.com/blog/1838019
今日推荐