繁体   English   中英

在SQL Server中将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);

在生产服务器上,我会编写一些表值函数来拆分列表,但是如果您需要快速的即席查询,则可以使用此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小提琴演示

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM