Solution to TSQL Beginners Challenge 15
declare @t table(id int identity, Sentence varchar(1000))
insert into @t(Sentence)
select 'This is T-SQL Beginners Challenge #15' union all
select 'I am a challenge competitor'
; with SplittedWords as (
select id, Sentence, substring(Sentence, 0, patindex('%' + space(1) + '%', Sentence)) as SubValue,
ltrim(substring(Sentence, patindex('% %', Sentence), len(Sentence))) as RestValue, 0 as H_Level
from @t
union all
select id, Sentence, substring(RestValue, 0, patindex('% %', RestValue + space(1))) as SubValue,
ltrim(substring(RestValue, patindex('% %', RestValue + space(1)), len(RestValue))) as RestValue, H_Level + 1 as H_Level
from SplittedWords
where len(RestValue) > 0
)
select ID, Sentence as [Original Sentence], Reversed_Sentece as [Reversed Sentece]
from @t as T
cross apply (
select SubValue + space(1)
from SplittedWords as SW
where SW.ID = T.ID
order by H_Level desc
for xml path('')
) as _DATA(Reversed_Sentece)
order by ID
Tags: