在 Sql 服务器中将 varchar 列表转换为 int

Convert varchar list to int in Sql Server

我需要一种方法将@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);

声明@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

好吧,在生产服务器上,我会编写一些 table 值函数来拆分列表,但是如果您需要快速的临时查询,这个 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