Find Substring in SQL

Viewed 196

I have to find substring as follows.

Data as below


aaaa.bbb.ccc.dddd.eee.fff.ggg 

qq.eeddde.rrr.t.hh.jj.jj.hh.hh 

ee.r.t.y.u.i.ii.

I want output as-


bbb

eeeddde

r

challenge I am facing is all have (.) as separator so sub-string is tough to work.

SELECT SUBSTRING(string,CHARINDEX('.',string)+1,
       (((LEN(string))-CHARINDEX('.', REVERSE(string)))-CHARINDEX('.',string))) AS Result 
  FROM [table] 

bbb

eeeddde

r

looking substring between first and secound (.)

then it might be between second and third (.)

4 Answers

Here is one method:

select left(v.str1, charindex('.', v.str1 + '.') - 1)
from t cross apply
     (values (stuff(t.string, 1, charindex('.', t.string + '.'), '')
     ) v(str1)

I assume (CHARINDEX) this is ms sql server. CROSS APPLY is handy for intermediate calculations.

SELECT t.pos, t1.pos,
  SUBSTRING(string, t.pos + 1, t1.pos - t.pos -1) AS Result 
FROM [table]
CROSS APPLY ( VALUES(CHARINDEX('.',string)) ) t(pos) 
CROSS APPLY ( VALUES(CHARINDEX('.',string, t.pos+1))) t1(pos) 

Just another option is to use a little XML

Example

Declare @YourTable table (ID int,SomeColumn varchar(max))
Insert Into @YourTable values
 (1,'aaaa.bbb.ccc.dddd.eee.fff.ggg')
,(2,'qq.eeddde.rrr.t.hh.jj.jj.hh.hh')
,(3,'ee.r.t.y.u.i.ii.')


Select ID
      ,SomeValue = convert(xml,'<x>' + replace(SomeColumn,'.','</x><x>')+'</x>').value('/x[2]','varchar(100)')
 From @YourTable

Returns

ID  SomeValue
1   bbb
2   eeddde
3   r

You can use left(), replace() and charindex() functions together :

select replace(
        replace(
               left(str,charindex('.',str,charindex('.',str)+1)),
               left(str,charindex('.',str)),
               ''
               ),
               '.'
               ,''
              ) as "Output"
  from t;

Demo

Related