经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MS SQL Server » 查看文章
Sql Server中使用特定字符分割字符串
来源:cnblogs  作者:时光巷尾  时间:2020/11/9 15:56:12  对本文有异议

在T-SQL中我们经常批量操作时都会对字符串进行拆分,可是SQL Server中却没有自带Split函数,所以要自己来实现了。这里将字符串分割以table形式输出
语法如下:

  1. SET ANSI_NULLS ON
  2. GO
  3. SET QUOTED_IDENTIFIER ON
  4. GO
  5. /*
  6. create by shuke.li 2020-9-15
  7. */
  8. create function [dbo].[SplitString]
  9. (
  10. @Input nvarchar(max), --input string to be separated
  11. @Separator nvarchar(max)=',', --a string that delimit the substrings in the input string
  12. @RemoveEmptyEntries bit=1 --the return value does not include array elements that contain an empty string
  13. )
  14. returns @TABLE table
  15. (
  16. [Id] int identity(1,1),
  17. [Value] nvarchar(max)
  18. )
  19. as
  20. begin
  21. declare @Index int, @Entry nvarchar(max)
  22. set @Index = charindex(@Separator,@Input)
  23. while (@Index>0)
  24. begin
  25. set @Entry=ltrim(rtrim(substring(@Input, 1, @Index-1)))
  26. if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'')
  27. begin
  28. insert into @TABLE([Value]) Values(@Entry)
  29. end
  30.  
  31. set @Input = substring(@Input, @Index+datalength(@Separator)/2, len(@Input))
  32. set @Index = charindex(@Separator, @Input)
  33. end
  34. set @Entry=ltrim(rtrim(@Input))
  35. if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'')
  36. begin
  37. insert into @TABLE([Value]) Values(@Entry)
  38. end
  39. return
  40. end

只要在新建查询里执行上面的代码,即完成了split函数的建立。
下面来测试这一函数的功能,测试所使用的的SQL脚本如下:

  1. declare @str1 varchar(max)
  2. set @str1 = 'CFER-3345-3323,CFER-0023-2299,CFER-0023-6677,CFER-0023-7678,CFER-4565-2299,CFER-0023-6678'
  3.  
  4. select * from [dbo].[SplitString](@str1, ',', 0)

结果显示如下图所示:

 

 最终使用方法和c#中的split函数是不是很相似!

原文链接:http://www.cnblogs.com/sgxw/p/13673618.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号