
拓狼
-
个人空间
- 组别:管理员
- 性别:
- 来自:北京 海淀
- 积分:1121
- 帖子:619
- 注册:
2007-05-23
|
字符串拆分函数Fn_Split
字符串拆分函数Fn_Split--王成辉翻译整理,转贴请注明出自微软BI开拓者www.windbi.com --原帖地址将以下代码拷贝到相应的数据库执行: CREATE FUNCTION fn_Split(@sText varchar(8000), @sDelim varchar(20) = ' ') RETURNS @retArray TABLE (idx smallint Primary Key, value varchar(8000)) AS BEGIN DECLARE @idx smallint, @value varchar(8000), @bcontinue bit, @iStrike smallint, @iDelimlength tinyintIF @sDelim = 'Space' BEGIN SET @sDelim = ' ' ENDSET @idx = 0 SET @sText = LTrim(RTrim(@sText)) SET @iDelimlength = DATALENGTH(@sDelim) SET @bcontinue = 1IF NOT ((@iDelimlength = 0) or (@sDelim = 'Empty')) BEGIN WHILE @bcontinue = 1 BEGIN--If you can find the delimiter in the text, retrieve the first element and --insert it with its index into the return table.
IF CHARINDEX(@sDelim, @sText)>0 BEGIN SET @value = SUBSTRING(@sText,1, CHARINDEX(@sDelim,@sText)-1) BEGIN INSERT @retArray (idx, value) VALUES (@idx, @value) END --Trim the element and its delimiter from the front of the string. --Increment the index and loop. SET @iStrike = DATALENGTH(@value) + @iDelimlength SET @idx = @idx + 1 SET @sText = LTrim(Right(@sText,DATALENGTH(@sText) - @iStrike)) END ELSE BEGIN --If you can抰 find the delimiter in the text, @sText is the last value in --@retArray. SET @value = @sText BEGIN INSERT @retArray (idx, value) VALUES (@idx, @value) END --Exit the WHILE loop. SET @bcontinue = 0 END END END ELSE BEGIN WHILE @bcontinue=1 BEGIN --If the delimiter is an empty string, check for remaining text --instead of a delimiter. Insert the first character into the --retArray table. Trim the character from the front of the string. --Increment the index and loop. IF DATALENGTH(@sText)>1 BEGIN SET @value = SUBSTRING(@sText,1,1) BEGIN INSERT @retArray (idx, value) VALUES (@idx, @value) END SET @idx = @idx+1 SET @sText = SUBSTRING(@sText,2,DATALENGTH(@sText)-1) END ELSE BEGIN --One character remains. --Insert the character, and exit the WHILE loop. INSERT @retArray (idx, value) VALUES (@idx, @sText) SET @bcontinue = 0 END ENDENDRETURN END下面是调用示例: declare @no char(100) set @no='abc,cdesefd,efddc,mgns,aa' select * from fn_Split(@no,',')
 拓狼 最后编辑于 2007-05-24 14:18:24
虽有智慧,不如乘势;虽有鎡基,不如待时。 君子学以聚之,问以辨之,宽以居之,仁以行之。 独学而无友,则孤陋而寡闻。
|