GO
/*
字符串分割函数
使用示例
select * from dbo.Func_StrSplit('x1,x2,x3,',',')
*/
create FUNCTION [dbo].[Func_StrSplit](
@Str nvarchar (max), -- 待处理字符串
@Split nvarchar (max) -- 分割字符串
)
RETURNS @ResTable TABLE ([Id] int,[Val] NVARCHAR(max))
as
BEGIN
DECLARE @Pos int, -- 当前匹配元素的开始位置
@Id int=1 -- 该匹配元素的Id值
SET @Str = @Str + @Split
SET @Pos = CHARINDEX(@Split,@Str)
WHILE (@pos <> 0)
BEGIN
if(len(SUBSTRING(@Str,1,@Pos - 1))>0)
begin
INSERT INTO @ResTable ([Id],[Val])
VALUES (@Id,SUBSTRING(@Str,1,@Pos - 1))
end
SET @Str = SUBSTRING(@Str,@pos +1,LEN(@Str))
SET @pos = CHARINDEX(@Split,@Str)
set @Id = @Id +1
END
RETURN
END
GO