如何反转字符串(SQL Server 2005,基于SET)

时间:2010-06-17 08:49:27

标签: sql-server-2005

E.g。

Declare @str varchar2(20)
Set @str = 'A Student'
Select Reverse(@str)

输出:

tnedutS A

预计会:

Student A

输出(使用Reverse)符合预期。但我的要求就是所描述的那个。

基于SET。

需要帮助

我正在使用SQL Server 2005

2 个答案:

答案 0 :(得分:1)

听起来你需要将字符串拆分为标记。有以下几种方法,请参阅以下内容。显然你需要将分隔符设置为''。 http://bit.ly/c3rUvM

然后,您可以按相反的顺序重建读取项目的字符串。

答案 1 :(得分:1)

修改原始回答误解了要求。我已经提出了一个修复方案,但现在完全没有必要拆分到角色级别了。至少它可能会提供一些想法!

WITH Strings AS
(
select 'A Student' as String
UNION ALL
select 'blah' as String
UNION ALL
select 'the quick brown fox jumped over the lazy dog' as String
),
SplitChars As
(
SELECT ROW_NUMBER() OVER (ORDER BY number) AS number, String, SUBSTRING(String,number,1) AS Ch FROM Strings
JOIN master.dbo.spt_values on number BETWEEN 1 AND LEN(String) AND type='P'
)


SELECT String,
replace(Stuff(
            (
            Select '' + Ch
            From SplitChars SC3
            WHERE SC3.String = SC.String
            Order By (SELECT COUNT(*) FROM SplitChars SC2 WHERE SC2.String = SC3.String AND SC2.Ch = ' ' AND SC2.number < SC3.number) desc, case when SC3.ch = ' ' then -1 else number end
            For Xml Path('')
            ),1, 0, ''), '&#x20;', ' ') AS Reversed
FROM SplitChars SC 
GROUP BY String

返回

  • 学生A
  • 嗒嗒
  • 狗懒得过来
  • 快跳了狐狸褐色