Reverse the order of words in TSQL

后端 未结 5 989
-上瘾入骨i
-上瘾入骨i 2020-12-06 23:31

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

5条回答
  •  佛祖请我去吃肉
    2020-12-06 23:33

    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.

提交回复
热议问题