1

I have the following Text:

"Original ----- The cow jumped over the moon ----- 20200723 --NEW-- The cow jumped over the sun ----- "

I'm trying to write a t-sql query that will extract everything between the string "Original ----- " and the following " ----- ", so my outcome would be:

"Original ----- The cow jumped over the moon ----- "

I've tried writing something like this:

declare @Text nvarchar(max) = 'Original ----- The cow jumped over the moon ----- 20200723 --NEW-- The cow jumped over the sun ----- '
select SUBSTRING(@Text, CHARINDEX('Original ----- ', @Text)
, CHARINDEX(' ----- ',@Text) - CHARINDEX('Original ----- ', @Text) + Len(' ----- '))

But it just returns Original -----. Please help!

2
  • 2
    CHARINDEX(' ----- ',@Text) - CHARINDEX('Original ----- ', @Text) finds the same occurrence of ' ----- ' twice. Commented Jul 23, 2020 at 19:26
  • Does this answer your question? A SQL Query to select a string between two known strings Commented Jul 23, 2020 at 20:13

2 Answers 2

1

CHARINDEX has a third, optional argument, which is the start. Modify your query as follows to begin looking for --- after the first occurence.

select SUBSTRING(@Text, CHARINDEX('Original ----- ', @Text)
, CHARINDEX(' ----- ',@Text, CHARINDEX('Original ----- ', @Text) + len('Original ----- '))) + '-----';

A quick Fiddle to demonstrate.

Sign up to request clarification or add additional context in comments.

Comments

1

You could rely on the fact that Original ----- is a fixed number of characters and hard code that value into your code. Then either use a where clause or a case expression to only apply it to those starting with Original -----

select 'Original ----- '+substring(col,16,charindex( '-----',col, 16)-11)
from t
where col like 'Original -----%';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.