Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A SQL Query to select a string between two known strings

I need a SQL query to get the value between two known strings (the returned value should start and end with these two strings).

An example.

"All I knew was that the dog had been very bad and required harsh punishment immediately regardless of what anyone else thought."

In this case the known strings are "the dog" and "immediately". So my query should return "the dog had been very bad and required harsh punishment immediately"

I've come up with this so far but to no avail:

SELECT SUBSTRING(@Text, CHARINDEX('the dog', @Text), CHARINDEX('immediately', @Text)) 

@Text being the variable containing the main string.

Can someone please help me with where I'm going wrong?

like image 411
coopertkm Avatar asked Aug 21 '13 15:08

coopertkm


People also ask

How do I find the string between two characters in SQL?

Using CHARINDEX function to get the input string. Using the SQL server substring function to extract characters between the starting position and ending position. Create table value function to extract characters. Using the table value function to extract characters using SQL substring function.

How can I get specific string from string in SQL?

Show activity on this post. SELECT SUBSTRING(LEFT(YOUR_FIELD, CHARINDEX('[', YOUR_FIELD) - 1), CHARINDEX(';', YOUR_FIELD) + 1, 100) FROM YOUR_TABLE WHERE CHARINDEX('[', YOUR_FIELD) > 0 AND CHARINDEX(';', YOUR_FIELD) > 0; Show activity on this post.

How do I extract a string between two delimiters in SQL Server?

If you're using SQL Server 2016 or newer you can use the STRING_SPLIT function. @squillman I am using SQL Server 2014. You can use a string splitting function.


2 Answers

The problem is that the second part of your substring argument is including the first index. You need to subtract the first index from your second index to make this work.

SELECT SUBSTRING(@Text, CHARINDEX('the dog', @Text) , CHARINDEX('immediately',@text) - CHARINDEX('the dog', @Text) + Len('immediately')) 
like image 130
orgtigger Avatar answered Sep 24 '22 10:09

orgtigger


I think what Evan meant was this:

SELECT SUBSTRING(@Text, CHARINDEX(@First, @Text) + LEN(@First),                   CHARINDEX(@Second, @Text) - CHARINDEX(@First, @Text) - LEN(@First)) 
like image 42
Data Masseur Avatar answered Sep 22 '22 10:09

Data Masseur