I would like to know how (if it is possible) to reverse the order of words returned from a TSQL string (varchar).
I know about the TSQL REVERS
Firstly, this is one of those cases where a CLR-based solution is going to be better, especially in terms of performance (the solution will invariable make use of iterations and string manipulation).
Here's a few lines of C# that achieves the result, although it has none of the SQL-CLR code you will need:
string original = "We want to tell you we all love StackOverflow";
string[] parts = original.Split(' ');
StringBuilder reversedString = new StringBuilder();
for (int i = parts.Length - 1; i >= 0; i--)
{
reversedString.Append(parts[i]);
reversedString.Append(" ");
}
string result = reversedString.ToString();
It would be even shorter with LINQ, but I thought I'd keep it simple. For a T-SQL solution, you can start with the splitString function in vzczc's post in the split post already mentioned.
Based on that, you do this:
DECLARE @ReverseString VARCHAR(MAX)
SET @ReverseString = ''
SELECT @ReverseString = @ReverseString + s + ' '
FROM
(
SELECT s, zeroBasedOccurance
FROM dbo.SplitString('We want to tell you we all love StackOverflow', ' ')
) A
ORDER BY A.zeroBasedOccurance DESC
SELECT @ReverseString
This should work, but the method it uses for concatenating the string back together is undocumented and may not work correctly in future versions of SQL Server. It will probably also perform very badly when compared to a CLR solution, so if you have the time to implement that, do so.