SQL Trivia – Reverse a string without using T-SQL REVERSE() function
Everyone knows that the REVERSE() function (as its name suggests) reverses a string’s value, MSDN link.
This post’s title talks about going the other way, but why? If we already have this function then why to reinvent the wheel.
But at times an Interviewer may trick you and asks this question randomly: “How will you reverse a string without using REVERSE() function? No loop, should be a single query.” People who have actually worked on CTEs and know about recursive CTEs can guess the answer and create the query on-spot. Actually he wants to know if you have really worked on CTEs & recursive CTEs, or just learned the concept, or do not know about this at all.
Let’s check this by a simple example:
DECLARE @StringToReverse VARCHAR(55) SET @StringToReverse = 'Reverse a string with out using REVERSE() function' ;WITH cte AS ( SELECT @StringToReverse AS string, CAST('' AS VARCHAR(55)) AS revStr, LEN(@StringToReverse) AS ln UNION ALL SELECT SUBSTRING(string,0,ln) AS string, CAST(revStr + SUBSTRING(string,ln,1) AS VARCHAR(55)) AS revStr, ln-1 AS ln FROM cte WHERE ln >= 1) SELECT @StringToReverse AS String, revStr FROM cte WHERE ln = 0
Note: In the code above check line numbers 5 & 7 containing CAST function, “CAST(” AS VARCHAR(55)) AS revStr” & “CAST(revStr + SUBSTRING(string,ln,1) AS VARCHAR(55))”.
Applying CAST or CONVERT function is necessary here as datatype & size of both the columns in the anchor & recursive part should be same. Otherwise SQL server will throw the following error:
Msg 240, Level 16, State 1, Line 4
Types don’t match between the anchor and the recursive part in column “revStr” of recursive query “cte”.
>> Check & Subscribe my [YouTube videos] on SQL Server.