I need to pull a specific substring from a string of the form:
foo=abc;bar=def;baz=ghi
For example, how would I get the value of \"bar\" from t
I have a generalized solution that works for this problem:
CREATE FUNCTION [dbo].[fn_StringBetween]
(
@BaseString varchar(max),
@StringDelim1 varchar(max),
@StringDelim2 varchar(max)
)
RETURNS varchar(max)
AS
BEGIN
DECLARE @at1 int
DECLARE @at2 int
DECLARE @rtrn varchar(max)
SET @at1 = CHARINDEX(@StringDelim1, @BaseString)
IF @at1 > 0
BEGIN
SET @rtrn = SUBSTRING(@BaseString, @at1
+ LEN(@StringDelim1), LEN(@BaseString) - @at1)
SET @at2 = CHARINDEX(@StringDelim2, @rtrn)
IF @at2 > 0
SET @rtrn = LEFT(@rtrn, @at2 - 1)
END
RETURN @rtrn
END
so if you run (just wrap your original string to be searched with ';' at beginning and end):
PRINT dbo.fn_StringBetween(';foo=abc;bar=def;baz=ghi;', ';bar=', ';')
you will get 'def' returned.