现在的位置: 首页 > 综合 > 正文

在将 varchar 值 ‘select * from soft where id=’ 转换成数据类型 int 时失败

2014年02月25日 ⁄ 综合 ⁄ 共 489字 ⁄ 字号 评论关闭

刚开始的存储过程:

create PROCEDURE [dbo].[mytest]
(
 @myTable  varchar(100),
 @myInt   int
)
AS
 declare @strSQL   varchar(1000);
 set @strSQL ='select * from ' + @myTable + ' where id=' + @myInt
 exec (@strSQL)
执行:exec mytest 'soft',10
显示错误:消息 245,级别 16,状态 1,过程 mytest,第 8 行
在将 varchar 值 'select * from soft where id=' 转换成数据类型 int 时失败。
搜了一下,发现字符串变量和整型变量不能用+,改成:
create PROCEDURE [dbo].[mytest]
(
 @myTable  varchar(100),
 @myInt   int
)
AS
 declare @strSQL   varchar(1000);
 set @strSQL ='select * from ' + @myTable + ' where id=' + cast(@myInt as varchar(10))
 exec (@strSQL)
通过。

抱歉!评论已关闭.