2

I have to ask you for something which is connetced with MSSQL.

So, I've got one column named Command(VARCHAR) which is a part of some table named TB_Commander.

This Column include results for example like (rows):

1.Delete o:2312312, c=312321
2.Add o:342342344, c=5

BTW. The thing I'd like to do is select substring from this rows which include only 'o:2312312' and for row number 2, only 'o:342342344'.

I'm stuck over here:

    select 
    SUBSTRING(Command,PATINDEX('%1%',Command), 
    CHARINDEX(',',Command,PATINDEX('%o=%',Command))-0) as OperationID 
    from TB_Commander 
    where IdRow = 921321

Sorry for my english...

Thanks for any hand...

Siva
  • 9,043
  • 12
  • 40
  • 63

3 Answers3

1

Try this ;)

select
substring(command, 
    patindex('%o:%', command) - 2, 
    patindex('%, c%', command)) as OperationID 
from TB_Commander 
where IdRow = 921321
Tristan
  • 1,004
  • 7
  • 14
0

This solution returns only the data you need, taking in to account length of patterns you use to extract the needed data:

SELECT
    SUBSTRING(command, 
    PATINDEX('%o:%', command) + LEN('o:'), 
    PATINDEX('%, c%', [FiscalizationRequest]) - PATINDEX('%o:%',[FiscalizationRequest]) - LEN('o:')
    ) as OperationID 
FROM TB_Commander;
Tadija Bagarić
  • 2,495
  • 2
  • 31
  • 48
0
declare @i int

declare @str varchar(1000)

set @str='interesting data'

declare @pattern varchar(1000)

set @pattern='eres'

SELECT @i=PATINDEX('%ter%', @str);  

select substring(@str,@i-4,len(@pattern)+4)
Zoe
  • 27,060
  • 21
  • 118
  • 148
Hasan Zafari
  • 355
  • 2
  • 6
  • Whilst this code snippet is welcome, and may provide some help, it would be [greatly improved if it included an explanation](//meta.stackexchange.com/q/114762) of *how* and *why* this solves the problem. Remember that you are answering the question for readers in the future, not just the person asking now! Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Aniket G Mar 15 '19 at 00:48