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?
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.
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.
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.
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'))
I think what Evan meant was this:
SELECT SUBSTRING(@Text, CHARINDEX(@First, @Text) + LEN(@First), CHARINDEX(@Second, @Text) - CHARINDEX(@First, @Text) - LEN(@First))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With