sql StringSplitWithIndex函数(SELECT * from StringSplitWithIndex('黄色,蓝色,黑色',','))
--SELECT * from StringSplitWithIndex('黄色,蓝色,黑色',',')
CREATE function [dbo].[StringSplitWithIndex]
(
@str nvarchar(max), --字符串
@spliter nvarchar(10)
) --分割符
returns @tb table(RowIndex int identity(1,1),Item nvarchar(256)) --返回对应表
AS
BEGIN
DECLARE @Num int,@Pos int, @NextPos int
SET @Num = 0
SET @Pos = 1
WHILE(@Pos <= LEN(@str))
BEGIN
SELECT @NextPos = CHARINDEX(@spliter, @str, @Pos)
IF (@NextPos = 0 OR @NextPos IS NULL)
SELECT @NextPos = LEN(@str) + 1
INSERT INTO @tb VALUES(RTRIM(LTRIM(SUBSTRING(@str, @Pos, @NextPos - @Pos))))
SELECT @Pos = @NextPos+1
END
return
END