I would like to know how (if it is possible) to reverse the order of words returned from a T-SQL string (varchar).
I know about the T-SQL REVERSE
function. but the function also reverses the letters in the word for example:
Input > We want to tell you we all love StackOverflow
Output > wolfrevOkcatS evol lla ew uoy llet ot tnaw eW
I want to actually achieve the following in T-SQL:
Input > We want to tell you we all love StackOverflow
Output > Stackoverflow love all we you tell to want We
The only slightly similar question I found anywhere was this one, however that includes splitting comma-separated strings which I do not need to do.
I'm sure there is a way to achieve the above, even if it's a custom function or SQL-CLR function.
I managed to split my string up using the following:
-- Create a space delimited string for testing
declare @str varchar(max)
select @str = 'We want to tell you we all love StackOverflow'
-- XML tag the string by replacing spaces with </x><x> tags
declare @xml xml
select @xml = cast('<x><![CDATA['+ replace(@str,' ',']]></x><x><![CDATA[') + ']]></x>' as xml)
-- Finally select values from nodes <x> and trim at the same time
select ltrim(rtrim(mynode.value('.[1]', 'nvarchar(50)'))) as Code
from (select @xml doc) xx
cross apply doc.nodes('/x') (mynode)
The problem now is trying to piece it all back together into one string in a backwards (DESC) order.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…