反转 T-SQL 中的单词顺序 [英] Reverse the order of words in T-SQL
问题描述
我想知道如何(如果可能)颠倒从 T-SQL 字符串 (varchar) 返回的词 的顺序.
I would like to know how (if it is possible) to reverse the order of words returned from a T-SQL string (varchar).
我知道 T-SQL REVERSE
函数.但该函数还反转单词中的字母,例如:
I know about the T-SQL REVERSE
function. but the function also reverses the letters in the word for example:
输入 >我们想告诉你,我们都喜欢 StackOverflow
输出 >wolfrevOkcatS evol lla ew uoy llet ot tnaw eW
我想在 T-SQL 中实际实现以下目标:
I want to actually achieve the following in T-SQL:
输入 >我们想告诉你我们都喜欢 StackOverflow
输出 >Stackoverflow 喜欢我们想要的一切
我在任何地方发现的唯一稍微相似的问题是这个,但是这包括拆分逗号分隔的字符串,我不需要这样做.
The only slightly similar question I found anywhere was this one, however that includes splitting comma-separated strings which I do not need to do.
我确信有一种方法可以实现上述目标,即使是自定义函数或 SQL-CLR 函数.
I'm sure there is a way to achieve the above, even if it's a custom function or SQL-CLR function.
我设法使用以下方法拆分了我的字符串:
I managed to split my string up using the following:
-- Create a space delimited string for testing
declare @str varchar(max)
select @str = 'We want to tell you we all love StackOverflow'
-- XML tag the string by replacing spaces with </x><x> tags
declare @xml xml
select @xml = cast('<x><![CDATA['+ replace(@str,' ',']]></x><x><![CDATA[') + ']]></x>' as xml)
-- Finally select values from nodes <x> and trim at the same time
select ltrim(rtrim(mynode.value('.[1]', 'nvarchar(50)'))) as Code
from (select @xml doc) xx
cross apply doc.nodes('/x') (mynode)
现在的问题是试图以向后 (DESC) 的顺序将它们全部拼凑成一个字符串.
The problem now is trying to piece it all back together into one string in a backwards (DESC) order.
推荐答案
您可以在 SQL 中创建一个小函数来反转字符串,如下所示:
You can create one small function in SQL to reverse a string like below:
DECLARE @source VARCHAR(MAX)
DECLARE @dest VARCHAR(MAX)
DECLARE @lenght INT
SET @source = 'We want to tell you we all love StackOverflow'
SET @dest = ''
WHILE LEN(@source) > 0
BEGIN
IF CHARINDEX(' ', @source) > 0
BEGIN
SET @dest = SUBSTRING(@source,0,CHARINDEX(' ', @source)) + ' ' + @dest
SET @source = LTRIM(RTRIM(SUBSTRING(@source,CHARINDEX(' ', @source)+1,LEN(@source))))
END
ELSE
BEGIN
SET @dest = @source + ' ' + @dest
SET @source = ''
END
END
SELECT @dest
这篇关于反转 T-SQL 中的单词顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!