本文介紹了在 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!