Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

sql - substring of variable length

I have a table with a column which contains strings like below.

RTSPP_LZ_AEN
RTSPP_LZ_CPS
RTSPP_LZ_HOUSTON
RTSPP_LZ_LCRA
RTSPP_LZ_NORTH
RTSPP_LZ_RAYBN
RTSPP_LZ_SOUTH
RTSPP_LZ_WEST
RTSPP_BTE_CC1 
RTSPP_BTE_PUN1 
RTSPP_BTE_PUN2

I need to get the substring from the second occurrence of _ till the end of string and as you can see the substring is not of fixed length. The first part is not always fixed it can change. As of now I am using the following code to achieve it.

SELECT SUBSTRING([String],CHARINDEX('_',[String],(CHARINDEX('_',[String])+1))+1,100)
FROM [Table]

As you can see I am taking an arbitrary large value as the length to take care of variable length. Is there a better way of doing it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use CHARINDEX in combination with REVERSE function to find last occurrence of _, and you can use RIGHT to get the specified number of characters from the end of string.

SELECT RIGHT([String],CHARINDEX('_',REVERSE([String]),0)-1)

SQLFiddle DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...