MSSQL 分割字符串

CREATE FUNCTION [dbo].[SplitToTable]
  (
      @SplitString nvarchar(max),--待分割的字符
      @Separator nvarchar(10)=' '--分隔符
  )
  RETURNS @SplitStringsTable TABLE
  (
  [id] int identity(1,1),
  [value] nvarchar(max)
 )
 AS
 BEGIN
    /*
    * 分割字符
    */ 
     DECLARE @CurrentIndex int;
     DECLARE @NextIndex int;
     DECLARE @ReturnText nvarchar(max);
     SELECT @CurrentIndex=1;
     WHILE(@CurrentIndex<=len(@SplitString))
         BEGIN
             SELECT @NextIndex=charindex(@Separator,@SplitString,@CurrentIndex);
             IF(@NextIndex=0 OR @NextIndex IS NULL)
                 SELECT @NextIndex=len(@SplitString)+1;
                 SELECT @ReturnText=substring(@SplitString,@CurrentIndex,@NextIndex-@CurrentIndex);
                 INSERT INTO @SplitStringsTable([value]) VALUES(@ReturnText);
                 SELECT @CurrentIndex=@NextIndex+1;
             END
     RETURN;
 END

 

posted @ 2018-03-07 16:10  烽火情怀  阅读(462)  评论(0编辑  收藏  举报