在Sql Server中将varchar list转换为int

时间:2015-04-16 16:35:40

标签: sql sql-server sql-server-2008 tsql ssms

我需要一种方法让@listOfPageIds被识别为数字列表而不是字符串。我尝试过转换,删除单引号......我真的不想在sql中做一个循环。

Declare @listOfPageIds varchar(50) ;

Set @listofPageIds = '2, 3, 4, 5, 6, 7, 14, 15';

select * from mytable p where p.PageId in( @listOfPageIds);

2 个答案:

答案 0 :(得分:3)

在生产服务器上我会为分割列表编写一些表值函数,但是如果你需要快速的即席查询,这个xml技巧可以工作

declare @listOfPageIds varchar(50), @data xml
declare @temp table(id int)

select @listofPageIds = '2, 3, 4, 5, 6, 7, 14, 15';
select @data = '<t>' + replace(@listofPageIds, ', ', '</t><t>') + '</t>'

insert into @temp
select
    t.c.value('.', 'int') as id
from @data.nodes('t') as t(c)

select * from @temp

<强> sql fiddle demo

答案 1 :(得分:0)

DECLARE @YourTable

DECLARE @yourTable TABLE (col1 INT);
INSERT INTO @yourTable VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15);

动态SQL解决方案

DECLARE @listOfPageIds nvarchar(255);
SET @listOfPageIds = '2, 3, 4, 5, 6, 7, 14, 15'
EXEC
(
'
DECLARE @yourTable TABLE (col1 INT);
INSERT INTO @yourTable VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
SELECT *
FROM @yourTable
WHERE col1 IN (' + @listOfPageIds+ ')'
)

递归CTE解决方案

DECLARE @listOfPageIds nvarchar(255);
SET @listOfPageIds = '2, 3, 4, 5, 6, 7, 14, 15'
SET @listOfPageIds = REPLACE(@listOfPageIds,' ','') + ',';  -- Put the end comma there instead of having to use a case statement in my query
                                                            -- As well as getting rid of useless white space with REPLACE()

WITH CTE
AS
(
    SELECT 1 row_count, CAST(SUBSTRING(@listOfPageIds,0,CHARINDEX(N',',@listOfPageIds,0)) AS NVARCHAR(255)) AS search_val, CHARINDEX(',',@listOfPageIds,0) + 1 AS starting_position
    UNION ALL
    SELECT row_count + 1,CAST(SUBSTRING(@listOfPageIds,starting_position,CHARINDEX(',',@listOfPageIds,starting_position) - starting_position) AS NVARCHAR(255)) AS search_val, CHARINDEX(',',@listOfPageIds,starting_position) + 1 AS starting_position
    FROM CTE
    WHERE row_count < (LEN(@listOfPageIds) - LEN(REPLACE(@listOfPageIds,',','')))
)

SELECT *
FROM @yourTable
WHERE col1 IN (SELECT CAST(search_val AS INT) FROM CTE)

结果(@yourTable的值为1-15):

col1
-----------
2
3
4
5
6
7
14
15