nowYouSeeMe
nowYouSeeMe

Reputation: 999

SQL Select part of string

I have a string that looks a bit like the following:

189 A 190 Merit 191 68.6

Now I want the value that falls between 190 and 191 - Merit.

Is this possible?

Upvotes: 0

Views: 1945

Answers (1)

RichardTheKiwi
RichardTheKiwi

Reputation: 107706

Being naive - you say you have a string (i.e. not a column).

declare @astring nvarchar(max);
set @astring = '189 A 190 Merit 191 68.6';

The next 2 statements strip out the part between 190 and 191.

set @astring = stuff(@astring,1,patindex('%190%',@astring)+2,'');
set @astring = stuff(@astring,patindex('%191%',@astring+'191'),len(@astring),'');
set @astring = LTRIM(RTRIM(@astring));

select @astring;  -- 'Merit'

If you had meant a table column, then

declare @t table (astring nvarchar(max));
insert @t select
'189 A 190 Merit 191 68.6' union all select
'189 A 19 Merit 191 68.6 oops bad string' union all select
'' union all select -- make sure it doesn't crash on empty string
null union all select -- ditto null
'189 C 190 Pass 191 50.1';

select astring, s2=stuff(s1,patindex('%191%',s1+'191'),len(s1),'')
from
(
select astring, s1=stuff(astring,1,patindex('%190%',astring+'190')+2,'')
from @t
) x

-- result
ASTRING                                      S2
189 A 190 Merit 191 68.6                     Merit
189 A 19 Merit 191 68.6 oops bad string      (null)
                                             (null)
(null)                                       (null)
189 C 190 Pass 191 50.1                      Pass

Upvotes: 2

Related Questions