1 CREATE FUNCTION [ dbo ] . [ Fn_Split ] 2 ( 3 @SplitString text , -- If you want to pass in the NText type, the following needs to be modified accordingly, and the comment behavior is the same as under NText 4 @Separator varchar ( 2 ) = ' , ' -- NVarChar(2) = N',' 5 ) 6 RETURNS @SplitStringsTable TABLE 7 ( 8 [ id ] int identity ( 1 , 1 ), 9 [ value ] varchar ( 8000 ) -- NVarChar(4000) 10 ) 11 AS 12 BEGIN 13 -- ------ @CurrentIndex records the value of the current Index, and @NextIndex records the value of the next Index in the string -- ----- 14 DECLARE @CurrentIndex int ; 15 DECLARE @NextIndex int ; 16 -- ----------@ReturnText: record the string between the character at CurrentIndex and NextIndex ----- ------------ 17 DECLARE @ReturnText varchar ( 8000 ); -- NVarChar(4000) 18 SELECT @CurrentIndex=1;----为@CurrentIndex赋初值 19 WHILE(@CurrentIndex<=DATALENGTH(@SplitString)) -- DATALENGTH(@SplitString)/2 20 BEGIN 21 SELECT @NextIndex=CHARINDEX(@Separator,@SplitString,@CurrentIndex); 22 IF(@NextIndex=0 OR @NextIndex IS NULL) 23 SELECT @NextIndex=DATALENGTH(@SplitString)+1;--DATALENGTH(@SplitString)/2 24 SELECT @ReturnText=SUBSTRING(@SplitString,@CurrentIndex,@NextIndex-@CurrentIndex); 25 INSERT INTO @SplitStringsTable([value]) 26 VALUES(@ReturnText); 27 SELECT @CurrentIndex=@NextIndex+1; 28 END 29 RETURN; 30 END
EX:
SELECT FN.value
FROM fn_split('A/B/C/D/E', '/') FN