在 SQL Server 中将 varchar 列表转换为 int

2021-09-10 00:00:00 sql tsql sql-server-2008 sql-server ssms

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

I need a way to have the @listOfPageIds be recognized as a list of numbers instead of strings. I have tried casting, removing the single quotes... I really don't want to do a loop in 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 技巧可以工作

Well on production server I'd write some table valued function for splitting lists, but if you need quick ad-hoc query, this xml trick could work

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 小提琴演示

相关文章