如何拆分逗号分隔的数据

时间:2013-06-09 14:15:30

标签: sql sql-server sql-server-2008

我有一个程序,输入以逗号分隔,如'1,2,3'。

我想查询

SELECT * FROM PERSON WHERE PERSON_ID IN(1,2,3). 

请注意PERSON_ID是整数。

4 个答案:

答案 0 :(得分:1)

我见过这类问题,所以我经常在其上发布一个博客here.

基本上你有三种选择(据我所知)

Gordon Lindoff建议的LIKE版本。

使用像这样的分割函数。

DECLARE @InList varchar(100)
SET @InList = '1,2,3,4'

SELECT MyTable.*
FROM MyTable
JOIN DelimitedSplit8K (@InList,',') SplitString
    ON MyTable.Id = SplitString.Item

或使用动态SQL。

DECLARE @InList varchar(100)
SET @InList = '1,2,3,4'

DECLARE @sql nvarchar(1000)

SET @sql = 'SELECT * ' + 
            'FROM MyTable ' + 
            'WHERE Id IN ('+@InList+') '

EXEC sp_executesql @sql

答案 1 :(得分:0)

SearchList = ',' + inputSearchTerm + ',';  /* e.g. inputSearchTerm is '1,2,3' */

SELECT * FROM PERSON WHERE CONTAINS(SearchList, ',' + cast(PERSON_ID as varchar) + ',');

答案 2 :(得分:0)

因为contains似乎有点矫枉过正(它专为模糊搜索而设计并使用全文索引),因为charindex()不是标准SQL,我厌恶varchar不在SELECT * FROM PERSON WHERE ','+@SearchList+',' like '%,'+cast(PERSON_ID as varchar(255))+',%'; 的答案有长度,让我给出一个替代方案:

@SearchList

1逗号的连接确保所有值都被分隔符包围。然后将这些值放在特定值附近,以防止10与{{1}}匹配。

请注意,这将特别有效,因为它需要全表扫描。

答案 3 :(得分:0)

以下是使用递归CTE进行此操作的方法:

declare @SearchList varchar(20)
set @SearchList= '1,2,3'
;with cte as
(select case charindex(',',@SearchList)
            when 0 then cast(@SearchList as int)
            else cast(left(@SearchList,charindex(',',@SearchList)-1) as int)
        end searchVal,
        case charindex(',',@SearchList)
            when 0 then ''
            else right(@SearchList,
                       len(@SearchList)-charindex(',',@SearchList) )
        end remainStr
 union all
 select case charindex(',',remainStr)
            when 0 then cast(remainStr as int)
            else cast(left(remainStr,charindex(',',remainStr)-1) as int)
        end searchVal,
        case charindex(',',remainStr)
            when 0 then ''
            else right(remainStr,
                       len(remainStr)-charindex(',',remainStr) )
        end remainStr
 from cte
 where remainStr > ''
)
select p.* 
from cte
join person p on cte.searchVal = p.person_id

SQLFiddle here