首页 > 代码库 > sql函数 StringSplit(SELECT * from Split('黄色,蓝色,黑色',','))

sql函数 StringSplit(SELECT * from Split('黄色,蓝色,黑色',','))

create function [dbo].[StringSplit]
(
@str nvarchar(max), --字符串
@spliter nvarchar(10)
) --分割符
returns @tb table(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

sql函数 StringSplit(SELECT * from Split('黄色,蓝色,黑色',','))