Reverse string in SQL Server

SQL Server has in build function REVERSE to reverse string. A T-SQL example is given below

1_Reverse string in SQL server

The function is very much direct. It takes an input string and returns the reversed string.

Another solution to reverse a string without using REVERSE function is given below

CREATE FUNCTION [dbo].fn_reversestring
(
    @string nvarchar(max)
)
RETURNS TABLE AS RETURN
(
WITH T1(number) AS (SELECT 1 UNION ALL SELECT 1),
T2(number)  AS (SELECT 1 FROM T1 AS a cross join T1 as b),
T3(number)  AS (SELECT 1 FROM T2 AS a cross join T2 as b),
T4(number)  AS (SELECT 1 FROM T3 AS a cross join T3 as b),
Nums(number) AS (SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) 
from T4)
SELECT STUFF( 
(SELECT   '' + SUBSTRING(@string,Nums.number,1)
FROM Nums order by Nums.number desc
FOR XML PATH('')),1,0,'') As ReversedString
)

The above function is an inline table valued function which uses tally table to reverse the input string. The logic is pretty simple. The statement SUBSTRING(@string,Nums.numer,1) breaks the string into rows of alphabets and then the string is concatenated in descending order.   The output of the function is given below.

2_Reverse string in SQL server

 

Like us on FaceBook Join the fastest growing SQL Server group on FaceBook

Leave a Reply

Your email address will not be published. Required fields are marked *