Reverse Order of Characters in a String

From SQLServerPedia

Jump to: navigation, search

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

Reverse the order of characters in a string

CREATE FUNCTION REVERSE_ORDER
               (@string VARCHAR(8000),
                @start  INT,
                @end    INT)
RETURNS VARCHAR(8000)
AS
  BEGIN
    IF @start < @end
      BEGIN
        RETURN 'please provide end character which is greater than start character'
      END
    
    IF @start > LEN(@string)
        OR @end > LEN(@string)
      BEGIN
        RETURN 'please provide start and end characters within the string'
      END
    
    RETURN SUBSTRING(@string,1,@start) + REVERSE(SUBSTRING(@string,@start,(@end - @start))) + SUBSTRING(@string,@end,(LEN(@string) - @end) + 1)
  END