CreateFUNCTION[dbo].[RecurrentSplit] ( @nvStrnvarchar(2000) --需要分割字符串 ,@vSepartevarchar(50) --分割字符串 ,@iIsHaveSeparteint--是否显示字符串 ,@iIsBeforeint--是否是后面的分割符(分割字符分割的顺序) ) RETURNS@Splittable ( IndexNo intdefault(0) --流水号 ,SplitName nvarchar(1000) --分割后字符串 ) AS BEGIN if(charindex(@vSeparte,@nvStr)<=0) --处理在整个字符串里都没有要分割,也就是字符串本身 begin insertinto@Split(SplitName) values(@nvStr) return end declare@iSeparteLenint ,@iEndHaveint--最后几个字符串是否是分割字符 ,@iStartHaveint--前面几个字符串是否是分割字符 select@iSeparteLen=len(@vSeparte) ,@iStartHave=0 ,@iEndHave=0 ,@iIsHaveSeparte=casewhen@iIsHaveSeparteisnull--默认值 then0 else@iIsHaveSeparte end ,@iIsBefore=casewhen@iIsBeforeisnull--默认值 then0 else@iIsBefore end if(@iIsBefore=1) --只有在处理前面字符串分割时才用 begin if(left(@nvStr,@iSeparteLen)<>@vSeparte)--处理前面几个分割字符一定是分割字符,不是就加 begin select@nvStr=@vSeparte+@nvStr ,@iStartHave=1 end end if(right(@nvStr,@iSeparteLen)<>@vSeparte)--处理最后几个分割字符一定是分割字符,不是就加 begin select@nvStr=@nvStr+@vSeparte ,@iEndHave=1 end; --分号一定不能少,因为用了with,是用公用表达式,在其前面一定要加; with CharCET(CharStr,StrLen,IndexNo) as ( selectsubstring(@nvStr,0 ,casewhen@iIsBefore=0thencharindex(@vSeparte,@nvStr)+@iSeparteLen elsecharindex(@vSeparte,@nvStr,charindex(@vSeparte,@nvStr)+@iSeparteLen) end ) CharStr ,casewhen@iIsBefore=0thencharindex(@vSeparte,@nvStr) elsecharindex(@vSeparte,@nvStr,charindex(@vSeparte,@nvStr)+@iSeparteLen) end StrLen ,0 IndexNo --第一次初始化 unionall selectsubstring(@nvStr ,casewhen@iIsBefore=0then StrLen+@iSeparteLen else StrLen end ,charindex(@vSeparte,@nvStr,StrLen+@iSeparteLen)-StrLen) CharStr ,charindex(@vSeparte,@nvStr,StrLen+@iSeparteLen) StrLen ,IndexNo+1 IndexNo --进行递归分割字符串 from CharCET where StrLen<len(@nvStr)-@iSeparteLen--处理递归结束语句,也就是不要让其生成无限弟归下去 ) insertinto@Split(IndexNo,SplitName) select IndexNo,casewhen@iIsHaveSeparte=0 thenreplace(CharStr,@vSeparte,'') else CharStr end CharStr from CharCET if(@iIsHaveSeparte=1) --是否显示分割字符串 begin update@Split--处理前面的分割字符串 set SplitName=casewhen@iStartHave=1 thenreplace(SplitName,@vSeparte,'') else SplitName end where IndexNo =0 update@Split--处理后面的分割字符串 set SplitName=casewhen@iEndHave=1 thenreplace(SplitName,@vSeparte,'') else SplitName end where IndexNo = (selectMax(IndexNo) from@Split) end RETURN END