我有一个功能:
ALTER FUNCTION [dbo].[func_ParseString] (@list nvarchar(MAX))
RETURNS @tbl TABLE (string VARCHAR(500) NOT NULL) AS
BEGIN
DECLARE @pos int,
@nextpos int,
@valuelen int
SELECT @pos = 0, @nextpos = 1
WHILE @nextpos > 0
BEGIN
SELECT @nextpos = charindex(', ', @list, @pos + 1)
SELECT @valuelen = CASE WHEN @nextpos > 0
THEN @nextpos
ELSE len(@list) + 1
END - @pos - 1
INSERT @tbl (string)
VALUES (substring(@list, @pos + 1, @valuelen))
SELECT @pos = @nextpos
END
RETURN
END
我有一张 table
当我尝试 select in 语句时,它仅返回逗号分隔字符串中名字的所有值
SELECT * FROM table
WHERE name IN (SELECT string COLLATE DATABASE_DEFAULT FROM [dbo].[func_ParseString]('Dan, Andy')
当我想返回第 1 行和第 3 行时,这只返回第 1 行
有人可以帮忙吗?
最佳答案
您的函数在 Andy 前面返回一个前导空白。
您应该使用LTRIM
函数来删除它。在函数中,插入@tbl:
INSERT @tbl (string)
VALUES (LTRIM (substring(@list, @pos + 1, @valuelen)))
或者当你调用函数时:
SELECT LTRIM(string) FROM [dbo].[func_ParseString] ('Dan, Andy')
关于sql - 字符串拆分sql函数仅返回字符串中的第一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17543934/