Reverse the order of words in TSQL

后端 未结 5 984
-上瘾入骨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:50

    declare @str varchar(100),
            @result varchar(100)
    
    set @str = 'We want to tell you we all love StackOverflow'
    
    ;with cte as 
    (
    select 1 pos_from, charindex(' ', @str) + 1 pos_to
    union all
    select pos_to, charindex(' ', @str + ' ', pos_to) + 1
    from cte
    where pos_to <= len(@str)
    )
    select @result = coalesce( @result + ' ', '') +substring(@str, pos_from, pos_to - pos_from - 1) 
    from cte
    order by pos_to desc
    
    select @result
    

提交回复
热议问题