Thursday, July 2, 2009

TSQL Challenge 3 to Reverse string without using Reverse() function

I have accept TSQL Challenge 3 from site and try to solve it.
Here is a URL of TSQL Challenge
http://beyondrelational.com/blogs/tc/archive/2009/05/24/tsql-challenge-3.aspx

Solved TSQL Challenge-3

DECLARE @t TABLE( ID INT IDENTITY, data VARCHAR(20))
INSERT INTO @t(data) SELECT 'Jacob'
INSERT INTO @t(data) SELECT 'Sebastian'

SET NOCOUNT ON

;WITH ReverseName AS
(
SELECT T.ID,T.data,CAST('' AS VARCHAR) AS ReverseData ,TotalLength=LEN(T.data),position=0 FROM @t T
UNION ALL
SELECT ReverseName.ID,ReverseName.data , CAST((ReverseName.ReverseData + substring(ReverseName.data,len(ReverseName.data)-position,1)) AS VARCHAR ) as ReverseData ,ReverseName.TotalLength,position=position+1 FROM ReverseName
where ReverseName.TotalLength>=position
)


SELECT ID,ReverseData AS [Reverse String] FROM ReverseName where position>TotalLength order by ID desc

OUTPUT:-

No comments: