CREATE FUNCTION fn_getstring ( @key VARCHAR(MAX) , @string VARCHAR(MAX) , @star INT , @step INT ) RETURNS VARCHAR(MAX) BEGIN DECLARE @result VARCHAR(MAX) SET @result = '' SELECT @result = @result + SUBSTRING(words, n, CHARINDEX(',', words + ',', n) - n) + ',' FROM ( SELECT @string words ) array JOIN dbo.Nums ON n <= LEN(words) AND SUBSTRING(@key + words, n, 1) = @key WHERE ( n - LEN(REPLACE(LEFT(words, n), @key, '')) + 1 ) BETWEEN @star AND @end RETURN SUBSTRING (@result,1, LEN(@result)-1) END