博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

字串分拆涵數

Posted on 2011-01-23 00:39  ☆Keep★Moving☆  阅读(192)  评论(0编辑  收藏  举报

/****************************************************************
Name:   fnSplitter

Description: 字串分拆

Usage: select result from fnSplitter('Data1|Data2|Data3','|')
    以某一個字符把字串分析開來
Return Table : Result
     ------
     Data1
     Data2
     Data3

History:
Date    Name    Description
****************************************************************/
create Function ufn_Splitter(@IDs Varchar(1050),@Delimited Varchar(5) )
Returns @Tbl_IDs Table (result Varchar(50)) As

Begin
-- Append comma
Set @IDs = @IDs + @Delimited
-- Indexes to keep the position of searching
Declare @Pos1 Int
Declare @pos2 Int

-- Start from first character
Set @Pos1=1
Set @Pos2=1

While @Pos1<Len(@IDs)
Begin
Set @Pos1 = CharIndex(@Delimited,@IDs,@Pos1)
Insert @Tbl_IDs Select Cast(Substring(@IDs,@Pos2,@Pos1-@Pos2) As Varchar(50))
-- Go to next non comma character
Set @Pos2=@Pos1+Len(@Delimited)
-- Search from the next charcater
Set @Pos1 = @Pos1+Len(@Delimited)
End
Return
End