反转 T

编程入门 行业动态 更新时间:2024-10-16 00:23:38
本文介绍了反转 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

本文发布于:2023-11-03 18:49:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555813.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!