Convert varchar list to int in Sql Server(在 SQL Server 中将 varchar 列表转换为 int)
问题描述
我需要一种方法让@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 小提琴演示
这篇关于在 SQL Server 中将 varchar 列表转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 SQL Server 中将 varchar 列表转换为 int


- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- SQL 临时表问题 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01