原文:在论坛中出现的比较难的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 tgo create table t(id int, ids varchar(100)) insert into tselect 1 , '3,8,83,92,215,7'go declare @a varchar(100) = '8,7' ;with ttas(select id, ids,@a+',' as a,ids+',' as ids_tfrom twhere ids like ('%' + REPLACE(@a,',', '%') + '%')), tttas(select id,ids, cast(a as varchar(max)) as a, cast(ids_t as varchar(max)) as ids_t , 1 as levelfrom 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 + 1from tttwhere charindex(',',a) > 0 ) select id, ids_tfrom (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 )awhere rownum = 1/*id ids_t1 3,83,92,215*/
来源:https://www.cnblogs.com/lonelyxmas/p/12020001.html