A SQL Query to select a string between two known strings A SQL Query to select a string between two known strings sql-server sql-server

A SQL Query to select a string between two known strings


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))


An example is this: You have a string and the character $

String :

aaaaa$bbbbb$ccccc

Code:

SELECT SUBSTRING('aaaaa$bbbbb$ccccc',CHARINDEX('$','aaaaa$bbbbb$ccccc')+1, CHARINDEX('$','aaaaa$bbbbb$ccccc',CHARINDEX('$','aaaaa$bbbbb$ccccc')+1) -CHARINDEX('$','aaaaa$bbbbb$ccccc')-1) as My_String

Output:

bbbbb