我有一个功能:
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
我有一张桌子
id --- name --- age
1 --- Dan --- 20
2 --- Chris --- 30
3 --- Andy --- 20
当我尝试select in语句时,它只返回逗号分隔字符串中第一个名字的所有值
SELECT * FROM table
WHERE name IN (SELECT string COLLATE DATABASE_DEFAULT FROM [dbo].[func_ParseString]('Dan, Andy')
当我想返回第1行和第3行
时,这只返回第1行有人可以帮忙吗?
答案 0 :(得分:3)
你的功能正在安迪面前领先一片空白。
您应该使用LTRIM
功能将其删除。在函数中,插入@tbl:
INSERT @tbl (string)
VALUES (LTRIM (substring(@list, @pos + 1, @valuelen)))
或致电函数时:
SELECT LTRIM(string) FROM [dbo].[func_ParseString] ('Dan, Andy')
答案 1 :(得分:0)
我不记得我在哪里找到了这个功能。我实现了它并且运行良好
ALTER FUNCTION [dbo].[StringSplit]
(
@delimited nvarchar(max),
@delimiter nvarchar(100)
) RETURNS @t TABLE
(
-- Id column can be commented out, not required for sql splitting string
id int identity(1,1), -- I use this column for numbering splitted parts
val nvarchar(max)
)
AS
BEGIN
declare @xml xml
set @xml = N'<root><r>' + replace(@delimited,@delimiter,'</r><r>') + '</r></root>'
insert into @t(val)
select
r.value('.','varchar(max)') as item
from @xml.nodes('//root/r') as records(r)
RETURN
END
GO
DECLARE @String NVARCHAR(max)
SET @String = 'Dan, Andy'
SELECT Val FROM [dbo].[StringSplit] (@String, ',')
答案 2 :(得分:0)
STRING_SPLIT在SQL Server 2016中可用。