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
You can use charindex and substring. For example, to search for the value of "baz":
declare @str varchar(128)
set @str = 'foo=abc;bar=def;baz=ghi'
-- Make sure @str starts and ends with a ;
set @str = ';' + @str + ';'
select substring(@str,
charindex(';baz=',@str) + len(';baz='),
charindex('=',@str,charindex(';baz=',@str)) - charindex(';baz=',@str) - 1)
Or for the value of "foo" at the start of the string:
select substring(@str,
charindex(';foo=',@str) + len(';foo='),
charindex('=',@str,charindex(';foo=',@str)) - charindex(';foo=',@str) - 1)
Here's a UDF to accomplish this (more readable version inspired by BlackTigerX's answer):
create function dbo.FindValueInString(
@search varchar(256),
@name varchar(30))
returns varchar(30)
as
begin
declare @name_start int
declare @name_length int
declare @value_start int
declare @value_end int
set @search = ';' + @search
set @name_start = charindex(';' + @name + '=',@search)
if @name_start = 0
return NULL
set @name_length = len(';' + @name + '=')
set @value_start = @name_start + @name_length
set @value_end = charindex(';', @search, @value_start)
return substring(@search, @value_start, @value_end - @value_start)
end
As you can see, this isn't easy in Sql Server :) Better do this in the client language, or normalize your database so the substrings go in their own columns.