首页 > 代码库 > 数据库自定义表值函数Split(@LongStr, @SplitStr, @IsDistinct )

数据库自定义表值函数Split(@LongStr, @SplitStr, @IsDistinct )

CREATE FUNCTION [dbo].[F3_Split](@LongStr VARCHAR(MAX),@SplitStr VARCHAR(100),@IsDistinct BIT)
RETURNS @RTable TABLE(ID INT IDENTITY PRIMARY KEY,ShortStr VARCHAR(MAX))
AS BEGIN
 IF ISNULL(@LongStr,‘‘)=‘‘ --表达式为空或NULL直接返回空表
  RETURN
 IF ISNULL(@SplitStr,‘‘)=‘‘ --分隔符为空直接返回一条记录的表(存放表达式)
 BEGIN
  INSERT INTO @RTable(ShortStr) SELECT @LongStr
  RETURN
 END
 DECLARE @Split_len INT
 DECLARE @LongStr_len INT
 SET @Split_len=LEN(@SplitStr) --分隔符的长度
 SET @LongStr_len=LEN(@LongStr) --目前表达式的长度
 WHILE CHARINDEX(@SplitStr,@LongStr)>0
 BEGIN
  DECLARE @ShortStr VARCHAR(1000) --分割后的字符串
  SET @ShortStr=SUBSTRING(@LongStr,1,CHARINDEX(@SplitStr,@LongStr)-1) --每次从第1个位置开始取分隔符所在的位置-1为一截
  SET @LongStr=SUBSTRING(@LongStr,CHARINDEX(@SplitStr,@LongStr)+@Split_len,(@LongStr_len-LEN(@ShortStr)-@Split_len)) --变换表达式的值为剩下的
  SET @LongStr_len=LEN(@LongStr) --变换表达式的长度
  IF @ShortStr<>‘‘ AND @IsDistinct=1
   INSERT INTO @RTable(ShortStr) SELECT @ShortStr
   WHERE NOT EXISTS(SELECT 1 FROM @RTable WHERE ShortStr=@ShortStr) --将分割出来的字符串放入表中
  ELSE IF @ShortStr<>‘‘
   INSERT INTO @RTable(ShortStr) SELECT @ShortStr
 END
 IF @LongStr<>‘‘  AND @IsDistinct=1 --如果最后一截没有分隔符,则直接进入表中
  INSERT INTO @RTable(ShortStr) SELECT @LongStr
  WHERE NOT EXISTS(SELECT 1 FROM @RTable WHERE ShortStr=@LongStr)
 ELSE IF @LongStr<>‘‘
  INSERT INTO @RTable(ShortStr) SELECT @LongStr
 RETURN
END

数据库自定义表值函数Split(@LongStr, @SplitStr, @IsDistinct )