您的位置:首页 > 数据库

换个思路"SQL2005下字符串字段内的字符排序"

2009-01-20 22:12 281 查看
这个是狙狙的sql解法。
http://blog.csdn.net/happyflystone/archive/2009/01/17/3819863.aspx
引用需求

今天和梁翁在群里聊天,小家伙突然抛出一个有意思的问题,那就是字符串字段内的字符串排序问题,比如有列col,有数据'RDGS' ,要求输出为'DGRS'。

依靠ascii来分解字符串的时候碰到相同字符串会有问题,和上面一篇oracle中的解法一样,索性根据字符串长度把sql语句写长点...这样还可以支持任何字符

我的想法

--测试数据

DECLARE @T TABLE(COL VARCHAR(10))

INSERT @T SELECT 'AWEAFSA'

INSERT @T SELECT 'DFSFA'

INSERT @T SELECT 'DQWF'

--数据生成

select col,

col2=replace((

select c as [data()] from(

select *,

c=case rn

when 1 then substring(col,1,1)

when 2 then substring(col,2,1)

when 3 then substring(col,3,1)

when 4 then substring(col,4,1)

when 5 then substring(col,5,1)

when 6 then substring(col,6,1)

when 7 then substring(col,7,1)

when 8 then substring(col,8,1)

when 9 then substring(col,9,1)

when 10 then substring(col,10,1)

else '' end from(

select col,rn from @t,(select rn=row_number() over(order by id) from sysobjects)b

where b.rn<=10)t1)t2 where c <>'' and col=t3.col order by c FOR XML PATH('')),' ','')

from @t t3

/*

col col2

----------
------------

AWEAFSA AAAEFSW

DFSFA ADFFS

DQWF DFQW

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐