标签:style blog http color io os ar div 2014
实际工作中,我们通常会有这样的业务场景,需要把一大串字符串,用某个特定的字符串分割出来,生成一张表。一下方法就很好的解决了这个问题。
1 IF EXISTS(SELECT 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID(‘fn_Split‘) AND XTYPE=‘FN‘) 2 BEGIN 3 DROP FUNCTION dbo.fn_Split 4 END 5 GO 6 --功 能:分割字符串表值函数 7 --参 数:@String 分割的字符串 8 -- @Delimiter 分隔符 9 --返 回 值:表 10 --创 建 人:maojw 11 --创建时间:2014-09-24 12 CREATE FUNCTION [dbo].[fn_Split]( 13 @String nvarchar (max), 14 @Delimiter nvarchar (10) 15 ) 16 RETURNS @ValueTable TABLE ([Value] NVARCHAR(MAX),[id] int) 17 BEGIN 18 DECLARE @NextString nvarchar(MAX), 19 @Pos int, 20 @NextPos int, 21 @CommaCheck nvarchar(1), 22 @id int 23 24 set @id=1 25 26 SET @NextString = ‘‘ 27 SET @CommaCheck = right(@String,1) 28 29 SET @String = @String + @Delimiter 30 31 SET @Pos = CHARINDEX(@Delimiter,@String) 32 SET @NextPos = 1 33 34 WHILE (@pos <> 0) 35 BEGIN 36 SET @NextString = SUBSTRING(@String,1,@Pos - 1) 37 38 INSERT INTO @ValueTable ( [Value],[id]) VALUES (@NextString,@id) 39 40 SET @String = SUBSTRING(@String,@pos +1,LEN(@String)) 41 42 SET @NextPos = @Pos 43 SET @pos = CHARINDEX(@Delimiter,@String) 44 45 set @id = @id +1 46 END 47 48 RETURN 49 END 50 GO
标签:style blog http color io os ar div 2014
原文地址:http://www.cnblogs.com/mjw1124/p/3990175.html