SQL分割字符串函數SQL里類似Split的分割字符串函數
SQL對字符串的處理能力比較弱,比如我要循環遍歷象1,2,3,4,5這樣的字符串,如果用數組的話,遍歷很簡單,但是T-SQL不支持數組,所以處理下來比較麻煩。下邊的函數,實現了象數組一樣去處理字符串。
一.用臨時表作為數組
1 /* 2 函 數 名:F_split 3 函數作用:分割字符串 4 函數參數: 5 @c ### 要分割的字符串 6 @split ### 分隔符號 7 示例: 8 Select * From dbo.F_split('a,b,c,d',',') 9 返回結果: 10 a 11 b 12 c 13 d 14 */ 15 CREATE FUNCTION F_split(@c VARCHAR(2000), 16 @split VARCHAR(2)) 17 returns @t TABLE( 18 col VARCHAR(20)) 19 AS 20 BEGIN 21 WHILE( Charindex(@split, @c) <> 0 ) 22 BEGIN 23 INSERT @t 24 (col) 25 VALUES (Substring(@c, 1, Charindex(@split, @c) - 1)) 26 27 SET @c = Stuff(@c, 1, Charindex(@split, @c), '') 28 END 29 30 INSERT @t 31 (col) 32 VALUES (@c) 33 34 RETURN 35 END 36 Go
二、按指定符號分割字符串,返回分割后的元素個數,方法很簡單,就是看字符串中存在多少個分隔符號,然后再加一,就是要求的結果
1 /* 2 函 數 名:Get_StrArrayLength 3 函數作用:返回分割字符串的長度 4 函數參數: 5 @str ### 要分割的字符串 6 @split ### 分隔符號 7 示例: 8 Select dbo.Get_StrArrayLength('78,1,2,3',',') 9 返回結果: 10 4 11 */ 12 Select dbo.Get_StrArrayLength('78,1,2,3',',') 13 CREATE FUNCTION Get_StrArrayLength (@str VARCHAR(1024), 14 @split VARCHAR(10) 15 ) 16 returns INT 17 AS 18 BEGIN 19 DECLARE @location INT 20 DECLARE @start INT 21 DECLARE @length INT 22 23 SET @str=Ltrim(Rtrim(@str)) 24 SET @location=Charindex(@split, @str) 25 SET @length=1 26 27 WHILE @location <> 0 28 BEGIN 29 SET @start=@location + 1 30 SET @location=Charindex(@split, @str, @start) 31 SET @length=@length + 1 32 END 33 34 RETURN @length 35 END 36 Go
三、按指定符號分割字符串,返回分割后指定索引的第幾個元素,象數組一樣方便
1 /* 2 函 數 名:Get_StrArrayStrOfIndex 3 函數作用:按指定符號分割字符串,返回分割后指定索引的第幾個元素,象數組一樣方便 4 函數參數: 5 @str ### 要分割的字符串 6 @split ### 分隔符號 7 @index ### 取第幾個元素 8 示例: 9 Select dbo.Get_StrArrayStrOfIndex('8,9,4',',',2) 10 返回結果: 11 9 12 */ 13 CREATE FUNCTION Get_StrArrayStrOfIndex(@str VARCHAR(1024), 14 @split VARCHAR(10), 15 @index INT) 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 24 SET @str=Ltrim(Rtrim(@str)) 25 SET @start=1 26 SET @next=1 27 SET @seed=Len(@split) 28 SET @location=Charindex(@split, @str) 29 30 WHILE @location <> 0 31 AND @index > @next 32 BEGIN 33 SET @start=@location + @seed 34 SET @location=Charindex(@split, @str, @start) 35 SET @next=@next + 1 36 END 37 38 IF @location = 0 39 SELECT @location = Len(@str) + 1 40 41 RETURN Substring(@str, @start, @location - @start) 42 END 43 Go