1、F_Split:分割字符串拆分爲數據表html
Create FUNCTION [dbo].[F_Split] ( @SplitString nvarchar(max), --源字符串 @Separator nvarchar(10)=' ' --分隔符號,默認爲空格 ) RETURNS @SplitStringsTable TABLE --輸出的數據表
( [id] int identity(1,1), [value] nvarchar(max) ) AS BEGIN DECLARE @CurrentIndex int; DECLARE @NextIndex int; DECLARE @ReturnText nvarchar(max); SELECT @CurrentIndex=1; WHILE(@CurrentIndex<=len(@SplitString)) BEGIN SELECT @NextIndex=charindex(@Separator,@SplitString,@CurrentIndex); IF(@NextIndex=0 OR @NextIndex IS NULL) SELECT @NextIndex=len(@SplitString)+1; SELECT @ReturnText=substring(@SplitString,@CurrentIndex,@NextIndex-@CurrentIndex); INSERT INTO @SplitStringsTable([value]) VALUES(@ReturnText); SELECT @CurrentIndex=@NextIndex+1; END RETURN; END --使用示例 select * FROm dbo.F_Split('111,b2222,323232,32d,e,323232f,g3222', ',')
結果爲數組
id valueide
-------- ---------------------------------------spa
1 111code
2 b2222htm
3 323232blog
4 32d索引
5 e字符串
6 323232fget
7 g3222
=========================================================================
2、F_SplitLength:獲取分割後的字符數組的長度
Create function [dbo].[F_SplitLength] ( @String nvarchar(max), --要分割的字符串 @Split nvarchar(10) --分隔符號 ) returns int as begin declare @location int declare @start int declare @length int set @String=ltrim(rtrim(@String)) set @location=charindex(@split,@String) set @length=1 while @location<>0 begin set @start=@location+1 set @location=charindex(@split,@String,@start) set @length=@length+1 end return @length end --調用示例 select dbo.F_SplitLength('111,b2222,323232,32d,e,323232f,g3222',',')
結果爲7。
=========================================================================
3、F_SplitOfIndex:獲取分割後特定索引的字符串
Create function [dbo].[F_SplitOfIndex] ( @String nvarchar(max), --要分割的字符串 @split nvarchar(10), --分隔符號 @index int --取第幾個元素 ) returns nvarchar(1024) as begin declare @location int declare @start int declare @next int declare @seed int set @String=ltrim(rtrim(@String)) set @start=1 set @next=1 set @seed=len(@split) set @location=charindex(@split,@String) while @location<>0 and @index>@next begin set @start=@location+@seed set @location=charindex(@split,@String,@start) set @next=@next+1 end if @location =0 select @location =len(@String)+1 return substring(@String,@start,@location-@start) end --使用示例 select dbo.F_SplitOfIndex('111,b2222,323232,32d,e,323232f,g3222',',', 3)
結果爲323232。
轉自:http://www.cnblogs.com/xiaofengfeng/archive/2012/06/01/2530930.html