SQL SERVICE 拆分字符串的表值函数

SQL代码

ALTER 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);
IF @ReturnText!=''
BEGIN
INSERT INTO @SplitStringsTable([value]) VALUES(@ReturnText);
END
SELECT @CurrentIndex=@NextIndex+1;
END
RETURN;
END

posted on 2013-07-26 19:53  张燕伟  阅读(391)  评论(0编辑  收藏  举报