一、按指定符号分割字符串,返回分割后的元素个数,方法很简单,就是看字符串中存在多少个分隔符号,然后再加一,就是要求的结果。

SQL分割字符串

SQL分割字符串CREATE function Get_StrArrayLength

SQL分割字符串(

SQL分割字符串  @str varchar(1024),  --要分割的字符串

SQL分割字符串  @split varchar(10)  --分隔符号

SQL分割字符串)

SQL分割字符串returns int

SQL分割字符串as

SQL分割字符串begin

SQL分割字符串  declare @location int

SQL分割字符串  declare @start int

SQL分割字符串  declare @length int

SQL分割字符串

SQL分割字符串  set @str=ltrim(rtrim(@str))

SQL分割字符串  set @location=charindex(@split,@str)

SQL分割字符串  set @length=1

SQL分割字符串  while @location<>0

SQL分割字符串  begin

SQL分割字符串    set @start=@location+1

SQL分割字符串    set @location=charindex(@split,@str,@start)

SQL分割字符串    set @length=@length+1

SQL分割字符串  end

SQL分割字符串  return @length

SQL分割字符串end

SQL分割字符串调用示例:select dbo.Get_StrArrayLength('78,1,2,3',',')

SQL分割字符串返回值:4

SQL分割字符串

SQL分割字符串二、按指定符号分割字符串,返回分割后指定索引的第几个元素,象数组一样方便

SQL分割字符串

SQL分割字符串CREATE function Get_StrArrayStrOfIndex

SQL分割字符串(

SQL分割字符串  @str varchar(1024),  --要分割的字符串

SQL分割字符串  @split varchar(10),  --分隔符号

SQL分割字符串  @index int --取第几个元素

SQL分割字符串)

SQL分割字符串returns varchar(1024)

SQL分割字符串as

SQL分割字符串begin

SQL分割字符串  declare @location int

SQL分割字符串  declare @start int

SQL分割字符串  declare @next int

SQL分割字符串  declare @seed int

SQL分割字符串

SQL分割字符串  set @str=ltrim(rtrim(@str))

SQL分割字符串  set @start=1

SQL分割字符串  set @next=1

SQL分割字符串  set @seed=len(@split)

SQL分割字符串  

SQL分割字符串  set @location=charindex(@split,@str)

SQL分割字符串  while @location<>0 and @index>@next

SQL分割字符串  begin

SQL分割字符串    set @start=@location+@seed

SQL分割字符串    set @location=charindex(@split,@str,@start)

SQL分割字符串    set @next=@next+1

SQL分割字符串  end

SQL分割字符串  if @location =0 select @location =len(@str)+1

SQL分割字符串 --这儿存在两种情况:1、字符串不存在分隔符号 2、字符串中存在分隔符号,跳出while循环后,@location为0,那默认为字符串后边有一个分隔符号。

SQL分割字符串  

SQL分割字符串  return substring(@str,@start,@location-@start)

SQL分割字符串end

SQL分割字符串调用示例:select dbo.Get_StrArrayStrOfIndex('8,9,4',',',2)

SQL分割字符串返回值:9

SQL分割字符串

SQL分割字符串三、结合上边两个函数,象数组一样遍历字符串中的元素

SQL分割字符串

SQL分割字符串create   function   f_splitstr(@SourceSql   varchar(8000),@StrSeprate   varchar(100))   

SQL分割字符串  returns   @temp   table(F1   varchar(100))   

SQL分割字符串  as     

SQL分割字符串  begin   

SQL分割字符串  declare   @ch   as   varchar(100)   

SQL分割字符串  set   @SourceSql=@SourceSql+@StrSeprate     

SQL分割字符串  while(@SourceSql<>'')   

SQL分割字符串                  begin   

SQL分割字符串                  set   @ch=left(@SourceSql,charindex(',',@SourceSql,1)-1)   

SQL分割字符串  insert   @temp   values(@ch)   

SQL分割字符串  set   @SourceSql=stuff(@SourceSql,1,charindex(',',@SourceSql,1),'')   

SQL分割字符串                  end   

SQL分割字符串  return   

SQL分割字符串  end   

SQL分割字符串    

SQL分割字符串

SQL分割字符串----调用

SQL分割字符串  select   *   from   dbo.f_splitstr('1,2,3,4',',') 

SQL分割字符串--结果:

SQL分割字符串1

SQL分割字符串2

SQL分割字符串3

SQL分割字符串

相关文章: