views:

52

answers:

2

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

+1  A: 

Sounds like you need to split you string into tokens. See the following for serveral 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.

TortoiseTNT
+1  A: 

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, ''), '&#x20;', ' ') AS Reversed
FROM SplitChars SC 
GROUP BY String

Returns

  • Student A
  • blah
  • dog lazy the over jumped fox brown quick the
Martin Smith