无法理解的SQL 从数据类型 nvarchar 转换为 bigint 时出错。

wxl_pilot 2007-10-30 11:58:46
exec sp_executesql N'Select count(1) from LVN_BlogPostCate Where ([PostCateIndex] in (@PostCateIndex0)) ',N'@PostCateIndex0
nvarchar(3)'
,@PostCateIndex0=N'2,5'

PostCateIndex字段是bitint
但是这样显式指定类型也不行?
...全文
1030 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
wxl_pilot 2007-10-30
  • 打赏
  • 举报
回复
declare @PostCateIndex0 nvarchar(3)
set @PostCateIndex0 =N '2,5'
exec sp_executesql N 'Select count(1) from LVN_BlogPostCate Where ([PostCateIndex] in (' + @PostCateIndex0 + '))'

这个也报语法错误
wxl_pilot 2007-10-30
  • 打赏
  • 举报
回复
那如果需要通过参数传递的话就不行了?
实在有点不明白,不都是被解析成 in (2,5)么?
hb_gx 2007-10-30
  • 打赏
  • 举报
回复
写错了,如果是int类型是不需要加 ' 的

declare @PostCateIndex0 nvarchar(3)  
set @PostCateIndex0 =N '2,5'
exec sp_executesql N 'Select count(1) from LVN_BlogPostCate Where ([PostCateIndex] in (' + @PostCateIndex0 + '))'
hb_gx 2007-10-30
  • 打赏
  • 举报
回复
PostCateIndex 字段应该是int类型吧,传进去的参数却是nvarchar ,这样当然有问题

不要把参数传进去,直接拼成动态Sql语句执行
declare @PostCateIndex0 nvarchar(3)
set @PostCateIndex0 =N '2,5 '
exec sp_executesql N 'Select count(1) from LVN_BlogPostCate Where ([PostCateIndex] in (''' + @PostCateIndex0 +''')) '


wxl_pilot 2007-10-30
  • 打赏
  • 举报
回复
exec sp_executesql N'Select count(1) from LVN_BlogPostCate Where ([PostCateIndex] in (@PostCateIndex0))',N'@PostCateIndex0

nvarchar(3)'
,@PostCateIndex0=N'2,5'

Sorry,上面那个似乎有点语法错误
这个是改正了的,执行就报
消息 8114,级别 16,状态 5,第 3 行
从数据类型 nvarchar 转换为 bigint 时出错。
wxl_pilot 2007-10-30
  • 打赏
  • 举报
回复
上面的执行:'+' 附近有语法错误。
谢谢hb_gx,麻烦你了
hb_gx 2007-10-30
  • 打赏
  • 举报
回复
@PostCateIndex0 参数是nvarchar类型,因为前面的字段是int类型,所以用 in 去比较的时候会先转换成把 @PostCateIndex0 转换成int 类型,

'2,5 '转换成int 当然会抱错了,



多个值用一个参数不好表示出来,要表示也只是是 set @PostCateIndex0 ='2'',''5' ,
然后用拼动态Sql语句


declare @PostCateIndex0 nvarchar(10)  
set @PostCateIndex0 ='2'',''5'
exec sp_executesql N'Select count(1) from LVN_BlogPostCate Where ([PostCateIndex] in (''' + @PostCateIndex0 + '''))'


因为是 in 可能有多个参数才这样处理的

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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