在将 nvarchar 值 '35,36' 转换成数据类型 int 时失败

icanjj 2008-10-13 03:16:58
我这样写就能运行:
select * from Item where ItemId in (35,36)

但如果将in里的35,36做为参数转过来,就出错,例如:

declare @st nvarchar(2000)
这里必须是nvarchar类型
select @st='35,36'
select * from Item where ItemId in (@st)
提示:在将 nvarchar 值 '35,36' 转换成数据类型 int 时失败

怎么解决呢?
...全文
1198 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
tim_spac 2008-10-13
  • 打赏
  • 举报
回复
另一种方式:

if exists (select 1 from sysobjects where name='fn_list2tb)
drop function dbo.fn_list2tb
go
create function dbo.fn_list2tb (@lst varchar(512))
returns @tb table (id int) as
begin
declare @pos int
set @lst = replace(replace(@lst,' ',''),',,',',')
set @pos = charindex(',',@lst)
while @pos>0 and @lst>'' begin
if @pos>1
insert into @tb values (left(@lst,@pos-1))
set @lst = stuff(@lst,1,@pos,'')
set @pos = charindex(',',@lst)
end
if @lst>''
insert into @tb values (@lst)
return
end
go

select a.*
from Item a
join dbo.fn_lst2tb(@lst) b on a.itemId=b.id
Cyril_Tam 2008-10-13
  • 打赏
  • 举报
回复
换种方式行不?

declare @first nvarchar(2000)
declare @second nvarchar(2000)
select @first='2'
select @second='3'
select * from table1 where id between @first and @second
pt1314917 2008-10-13
  • 打赏
  • 举报
回复

declare @st nvarchar(2000)
select @st='35,36'
select * from Item where charindex(','+ltrim(ItemId)+',',','+@st+',')>0
hyde100 2008-10-13
  • 打赏
  • 举报
回复
动态sql
select @st='''35''+'',36'''
exec('select * from Item where ItemId in '+@st)
中国风 2008-10-13
  • 打赏
  • 举报
回复

declare @st nvarchar(2000)
select @st='35,36'
select * from Item where patindex('%,'+rtrim(ItemId)+',%',','+@st+',')>0
csdyyr 2008-10-13
  • 打赏
  • 举报
回复

exec('select * from Item where ItemId in ('+@t+')')
水族杰纶 2008-10-13
  • 打赏
  • 举报
回复
select @st='''35''+'',36'''
exec('select * from Item where ItemId in '+@st)

34,593

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧