SQL Server中自定义Split函数

这是一个蛮久之前写的一个函数,因为写sql程序碰到了需要拆分字符串的情况。在vb中提供有这样的函数,或者在其他的语言的类库中的string对象也提供有拆分一个字符串到数组中的split函数。或许因为sql没有数组类型,所以也没有创建这样的字符串处理函数。我写了一个自定义函数来实现类似的功能。  
   
  sql没有数组类型,但是可以相似的有table类型数值。可以这么设计,函数输入值为一个字符类型(varchar之类的)的参数,返回一个table类型的结果。  
   
  定义如下:  
   
  1,参数定义和说明  
   
  输出参数:@splitString   varchar(8000)   --   需要Split的字符串  
                      @separate   varchar(10)     ---分隔符  
   
  返回:@returnTable   table(col_Value   varchar(20))     --单个字符长度可以按照需要修改  
   
   
  2,函数体  
   
  CREATE   FUNCTION   SplitStr   (@splitString   varchar(8000),   @separate   varchar(10))  
  RETURNS   @returnTable   table(col_Value   varchar(20))  
  AS  
   
  BEGIN  
   
  declare   @thisSplitStr   varchar(20)  
  declare   @thisSepIndex   int  
  declare   @lastSepIndex   int  
   
  set   @lastSepIndex   =   0  
   
  if   Right(@splitString   ,len(@separate))   <>   @separate   set   @splitString   =   @splitString   +   @separate  
  set   @thisSepIndex   =   CharIndex(@separate,@splitString   ,@lastSepIndex)  
   
  while   @lastSepIndex   <=   @thisSepIndex  
  begin  
                    set   @thisSplitStr   =   SubString(@splitString   ,@lastSepIndex,@thisSepIndex-@lastSepIndex)  
                    set   @lastSepIndex   =   @thisSepIndex   +   1  
                    set   @thisSepIndex   =   CharIndex(@separate,@splitString   ,@lastSepIndex)  
                    insert   into   @returnTable   values(@thisSplitStr)  
  end  
  return  
   
  END  
   
     
   
     
   
     
   
  下面是使用的例子:  
   
  使用实例:select   *   from   SplitStr(‘123,456,789’,’,’)  
   
  结果:  
   
  col_value  
  -----------------------------------------------------------------------------  
  123  
  456  
  789   
   
posted @ 2009-02-25 17:01  Rick Sun  阅读(1280)  评论(0编辑  收藏  举报