T-SQL to get string between two strings

by Amol 17. July 2013 09:17

Below is the user defined function created in SQL Server to find the string between two strings.

 

CREATE FUNCTION dbo.udf_GetStringBetween2Strings 
(
	@String varchar(max), 
	@FirstString varchar(256), 
	@SecondString varchar(256)
)
RETURNS VARCHAR(max) 
AS
BEGIN

	DECLARE @FirstPosition int,  @SecondPosition int
	SET @FirstPosition = CHARINDEX(@FirstString,@String) + LEN(@FirstString)
	SET @SecondPosition = CHARINDEX(@SecondString,@String) 
	RETURN (SELECT SUBSTRING(@String, @FirstPosition, @SecondPosition - @FirstPosition))

END
GO

DECLARE @MyString varchar(256) = 'Bla bla bla xyxz Find my name Amol Rajmane in this string.'
SELECT dbo.udf_GetStringBetween2Strings (@MyString, 'Find my name ', ' in this') 
GO

 

 

Result is "Amol Rajmane"

Tags: ,

General

Category

Recent Posts

Tag cloud