在论坛中出现的比较难的sql问题:13(循环替换问题 过滤各种标点符号)

原文: 在论坛中出现的比较难的sql问题:13(循环替换问题 过滤各种标点符号)

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


去掉一个字段中的标点符号的SQL语句怎么写

http://bbs.csdn.net/topics/390621077?page=1#post-395850514

比如有一个字段    题名
         1       水尼“十万”个为什么
         2      当代工人:市场化的演变与趋势
         3      当代画家  (东北卷)

想把这个字段中的标点符号去掉,请教各位大侠SQL 语句该怎么写。

我的解法是,通过新建一个符号表,里面存储要替换的各种符号,然后通过循环,把这些符号替换了,

如果数据多了,应该效率不太好:


  
  
  1. if object_id('t') is not null
  2. drop table t
  3. go
  4. create table t( id int,title nvarchar( 100))
  5. insert into t
  6. select 1, '水尼“十万”个为什么' union all
  7. select 2, '当代工人:市场化的演变与趋势' union all
  8. select 3, '当代画家(东北卷)' union all
  9. select 4, '当代画家:“北京篇:;”'
  10. if object_id( 'symbol') is not null
  11. drop table symbol
  12. go
  13. --建立一个标点符号的表,你可以往里面加各种你想替换的标点符号
  14. create table symbol (n nvarchar( 10));
  15. insert into symbol
  16. select '“' union all
  17. select '”' union all
  18. select ':' union all
  19. select ';'
  20. go
  21. if exists( select * from sys.objects where name = 'fn_replace_symbol')
  22. drop function dbo.fn_replace_symbol;
  23. go
  24. create function dbo.fn_replace_symbol(@n nvarchar( 1000))
  25. returns nvarchar( 1000)
  26. as
  27. begin
  28. declare @i int;
  29. declare @ count int;
  30. set @i = 1
  31. set @ count = ( select count(*) from symbol);
  32. while @i <= @count
  33. begin
  34. ;with t
  35. as
  36. (
  37. select n,
  38. row_number() over( order by @@servername) as rownum
  39. from symbol
  40. )
  41. select @n = replace(@n,( select n from t where rownum = @i), '')
  42. set @i = @i + 1
  43. end
  44. return @n
  45. end
  46. go
  47. --替换效果
  48. select * ,
  49. dbo.fn_replace_symbol(title) as 替换完后的字符
  50. from t
  51. /*
  52. id title 替换完后的字符
  53. 1 水尼“十万”个为什么 水尼十万个为什么
  54. 2 当代工人:市场化的演变与趋势 当代工人市场化的演变与趋势
  55. 3 当代画家(东北卷) 当代画家(东北卷)
  56. 4 当代画家:“北京篇:;” 当代画家北京篇
  57. */


猜你喜欢

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