T-SQL 实现一个简单的 Split 函数,供朋友们学习参考。
DECLARE @list VARCHAR(100), @cnt INT, @idxStart INT, @idxEnd INT
DECLARE @sites TABLE(id INT)
SET @list = '23, 34, 44, 56, 78';
--SET @list = '23';
SET @list = replace(@list, ' ', '')
IF(RIGHT(@list, 1)<>',')
SET @list = @list + ','
SET @cnt = len(replace(@list, ',', ',,'))-len(@list);
SET @idxStart = 0
SET @idxEnd = 0
WHILE @cnt > 0
BEGIN
SET @idxEnd = charindex(',', @list, @idxStart)
INSERT INTO @sites VALUES(convert(INT, substring(@list, @idxStart, @idxEnd-@idxStart)));
SET @idxStart = @idxEnd + 1
SET @cnt = @cnt - 1
END
SELECT * FROM @sites;