2013-07-09 132 views
2

我有一个函数:字符串分割SQL函数只返回第一个词串

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 * FROM table 
WHERE name IN (SELECT string COLLATE DATABASE_DEFAULT FROM [dbo].[func_ParseString]('Dan, Andy') 

这只能返回第1行,当我想返回行1和3

有人可以帮忙吗?

回答

3

您的功能正在返回Andy前面的空白处。

您应该使用LTRIM函数将其删除。无论是在功能,在插入到@tbl:

INSERT @tbl (string) 
     VALUES (LTRIM (substring(@list, @pos + 1, @valuelen))) 

或当你调用函数:

SELECT LTRIM(string) FROM [dbo].[func_ParseString] ('Dan, Andy') 
+0

为我工作,我用它当我打电话的功能,因此使用你给了第二个选项,非常感谢你 – Win

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, ',') 
0

STRING_SPLIT SQL服务器2016年提供