Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 934
Ram Avatar asked Jul 31 '13 15:07

Ram


People also ask

How do I find the length of a substring in SQL?

Dynamically locate the starting and end character Using the SQL Server Substring function, the numeric sub-set of a string from the column col is transformed using CHARINDEX. You can also use the SQL string function PATINDEX to find the initial position and length parameter of the SQL SUBSTRING function.

What is the difference between substring and Charindex?

CHARINDEX function in SQL queries It works reverse to the SUBSTRING function. The substring() returns the string from the starting position however the CHARINDEX returns the substring position. In the below example, we retrieve the position of substring SQLSHACK.COM using the CHARINDEX.

Which is faster substring or left?

There is no difference at all between left and substring because left is translated to substring in the execution plan. Save this answer.

How many arguments does substr () will take?

The SUBSTRING function requires two arguments and can take a third. The first argument is the string to be found and it can be stated either as a string or as a column. The second argument is the placement in the string of the first character to be returned.


1 Answers

This seems nice to me:

declare @yourvariable nvarchar(max)

set @yourvariable=(Select
(SELECT  distinct ','+yourcolumn
from yourtable 
for xml path('')) )

select substring(@yourvariable,2,len(@yourvariable))
like image 185
KZiovas Avatar answered Sep 21 '22 02:09

KZiovas