Substring with Start and End Parameters

From SQLServerPedia

Jump to: navigation, search

See Also: Main_Page - Transact SQL Code Library - String Manipulation Functions


Get a string between two locations

-- get substring between two locations in the string  
CREATE PROC GET_STRING_BETWEEN_TWO_CHARACTERS
           @string VARCHAR(2000),
           @start  INT,
           @end    INT
AS
  DECLARE  @output VARCHAR(2000)
  
  IF @start >= LEN(@string)
    BEGIN
      SELECT 'please choose a different starting character'
      
      RETURN
    END
  ELSE
    IF @start >= @end
      BEGIN
        SELECT 'please choose the end character which is greater than the start character'
        
        RETURN
      END
  
  SELECT @output = SUBSTRING(@string,@start,(@end - @start))
  
  PRINT @output

GO