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

这个是狙狙的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

*/

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值