Home / Others / Reverse a string without using REVERSE() function in SQL
Reverse a string without using REVERSE() function in SQL

Functions are created for to do a specific task in any language. eg: REVERSE() function (as its name suggests) reverses a string’s value. Every function have some logic behind that. Sometimes interviewer asked this question "Reverse a string without using REVERSE() function in sql or other language?". Find below code for String reverse without using T-SQL function.


CREATE function ReverseString(@input varchar(max))
returns varchar(max)
AS
BEGIN
 DECLARE @i int,
    @Result varchar(max)
     SET @Result=''
     SET @i = 1
       WHILE @i <= LEN(@input)
 BEGIN
   SET @Result = SUBSTRING(@input,@i,1) + @Result
   SET @i=@i + 1
 END
     RETURN @Result
END

 

SELECT dbo.StringReverse('ABC')