牛骨文教育服务平台(让学习变的简单)
博文笔记

SQL自定义函数split 将数组(分隔字符串)返回阵列(表)

创建时间:2007-09-29 投稿人: 浏览次数:297

 SQL自定义函数split

Create Function Split(@Strs As Nvarchar(1024),@Separator as Nvarchar(10),@Index as Int) 
Returns Nvarchar(1024) As 
begin
     
Declare @i As Int, @charpos As Nvarchar(1024)
     
Set @charpos = @Strs
     
Set @i = 1
     
If @Index < 0
            
Begin
              
Set @charpos = "超出下界"   
            
End
     
Else
       
Begin  
       
While @i <= (@Index - 1)
            
Begin
             
If CharIndex(@Separator, @charpos) > 0
              
Begin
                 
Set @charpos = Substring(@charpos, CharIndex(@Separator, @charpos) + 1, Len(@charpos) - CharIndex(@Separator, @charpos))
              
End
       
Else
       
Begin
         
Set @charpos = "超出上界"
         
Break
       
End
      
Set @i = @i + 1
    
End   

   
If @charpos <> "超出上界"
        
Begin
         
If CharIndex(@Separator, @charpos) > 0  
             
Begin
                   
Set @charpos = Left(@charpos, CharIndex(@Separator, @charpos) - 1)
              
End
        
End
      
End
     
Return @charpos
End
--调用
select dbo.Split("sdf|abc|csc|aldsfj|sfj|取出原素|asdf|adf|...","|",6)
--返回 取出原素
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。