新野县12345_后端

字符串分割函数.sql 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. USE [XinYe12345]
  2. GO
  3. /****** Object: UserDefinedFunction [dbo].[Get_StrArrayStrOfIndex] Script Date: 01/14/2020 13:10:19
  4. -- 20200114 lihai 分割的字符串
  5. ******/
  6. SET ANSI_NULLS ON
  7. GO
  8. SET QUOTED_IDENTIFIER ON
  9. GO
  10. ALTER function [dbo].[Get_StrArrayStrOfIndex]
  11. (
  12. @str varchar(1024), --要分割的字符串
  13. @split varchar(10), --分隔符号
  14. @index int --取第几个元素
  15. )
  16. returns varchar(1024)
  17. as
  18. begin
  19. declare @location int
  20. declare @start int
  21. declare @next int
  22. declare @seed int
  23. set @str=ltrim(rtrim(@str))
  24. set @start=1
  25. set @next=1
  26. set @seed=len(@split)
  27. set @location=charindex(@split,@str)
  28. while @location<>0 and @index>@next
  29. begin
  30. set @start=@location+@seed
  31. set @location=charindex(@split,@str,@start)
  32. set @next=@next+1
  33. end
  34. if @location =0 select @location =len(@str)+1
  35. --这儿存在两种情况:1、字符串不存在分隔符号 2、字符串中存在分隔符号,跳出while循环后,@location为0,那默认为字符串后边有一个分隔符号。
  36. return substring(@str,@start,@location-@start)
  37. end
  38. --调用示例:select dbo.Get_StrArrayStrOfIndex('8,9,4',',',2)
  39. --返回值:9