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
基础教程推荐
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01