在论坛中出现的比较难的sql问题:12(递归问题2 拆分字符串)

最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了。

所以,觉得有必要记录下来,这样以后再次碰到这类问题,也能从中获取解答的思路。


请教一个MSSQLSELECT语名的写法 

http://bbs.csdn.net/topics/390649166?page=1#post-396149924

表结构
id  ids
1   3,8,83,92,215,7

传入一个值8,92要取出3,83,215,7
即是取出不存在于传入ID串其它所有ID都取出来.
请问这个SELECT 语语应该怎么写。

递归replace,我的解法:

drop table t
go

create table t(id int,  ids varchar(100))

insert into t
select 1 ,  '3,8,83,92,215,7'
go



declare @a varchar(100) = '8,7'

;with tt
as
(
select id, ids,@a+',' as a,ids+',' as ids_t
from t
where ids like ('%' + REPLACE(@a,',', '%') + '%')
),

ttt
as
(
select id,ids,
       cast(a as varchar(max)) as a,
       cast(ids_t as varchar(max)) as ids_t ,
       1  as level
from tt

union all

select id,ids,
       cast(stuff(a,1,charindex(',',a),'') as varchar(max)) ,
       cast(replace(ids_t,left(a,charindex(',',a)),'') as varchar(max)),
       level + 1
from ttt
where charindex(',',a) > 0

)


select id, ids_t
from 
(
select id, ids,left(ids_t,len(ids_t)-1) as ids_t,
       ROW_NUMBER() over(partition by id order by level desc) as rownum 
from ttt 
)a
where rownum = 1
/*
id	ids_t
1	3,83,92,215
*/


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值