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

原文: 在论坛中出现的比较难的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,我的解法:


   
   
  1. drop table t
  2. go
  3. create table t( id int, ids varchar( 100))
  4. insert into t
  5. select 1 , '3,8,83,92,215,7'
  6. go
  7. declare @a varchar( 100) = '8,7'
  8. ;with tt
  9. as
  10. (
  11. select id, ids,@a+ ',' as a,ids+ ',' as ids_t
  12. from t
  13. where ids like ( '%' + REPLACE(@a, ',', '%') + '%')
  14. ),
  15. ttt
  16. as
  17. (
  18. select id,ids,
  19. cast(a as varchar( max)) as a,
  20. cast(ids_t as varchar( max)) as ids_t ,
  21. 1 as level
  22. from tt
  23. union all
  24. select id,ids,
  25. cast( stuff(a, 1, charindex( ',',a), '') as varchar( max)) ,
  26. cast( replace(ids_t, left(a, charindex( ',',a)), '') as varchar( max)),
  27. level + 1
  28. from ttt
  29. where charindex( ',',a) > 0
  30. )
  31. select id, ids_t
  32. from
  33. (
  34. select id, ids, left(ids_t, len(ids_t) -1) as ids_t,
  35. ROW_NUMBER() over( partition by id order by level desc) as rownum
  36. from ttt
  37. )a
  38. where rownum = 1
  39. /*
  40. id ids_t
  41. 1 3,83,92,215
  42. */


发布了416 篇原创文章 · 获赞 135 · 访问量 94万+

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12020001.html
今日推荐