2013-07-09 130 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年提供