Reputation: 1111
E.g.
Declare @str varchar2(20)
Set @str = 'A Student'
Select Reverse(@str)
Output:
tnedutS A
Expected being:
Student A
The output(using Reverse) is as expected. But my requirement is the one described.
Help needed with SET BASED.
I am using SQL Server 2005
Upvotes: 1
Views: 2249
Reputation: 271
Sounds like you need to split you string into tokens. See the following for several ways you can do this. Obviously you'll need to set the delimiter to ' '. http://bit.ly/c3rUvM
You can then rebuild your string reading the items in the reverse order.
Upvotes: 1
Reputation: 453212
Edit Original answer misunderstood the requirement. I've Bodged a fix but the split down to character level is completely unnecessary now. At least it might give some ideas!
WITH Strings AS
(
select 'A Student' as String
UNION ALL
select 'blah' as String
UNION ALL
select 'the quick brown fox jumped over the lazy dog' as String
),
SplitChars As
(
SELECT ROW_NUMBER() OVER (ORDER BY number) AS number, String, SUBSTRING(String,number,1) AS Ch FROM Strings
JOIN master.dbo.spt_values on number BETWEEN 1 AND LEN(String) AND type='P'
)
SELECT String,
replace(Stuff(
(
Select '' + Ch
From SplitChars SC3
WHERE SC3.String = SC.String
Order By (SELECT COUNT(*) FROM SplitChars SC2 WHERE SC2.String = SC3.String AND SC2.Ch = ' ' AND SC2.number < SC3.number) desc, case when SC3.ch = ' ' then -1 else number end
For Xml Path('')
),1, 0, ''), ' ', ' ') AS Reversed
FROM SplitChars SC
GROUP BY String
Returns
Upvotes: 1