刚开始的存储过程:
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
(
@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 时失败。
在将 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)
(
@myTable varchar(100),
@myInt int
)
AS
declare @strSQL varchar(1000);
set @strSQL ='select * from ' + @myTable + ' where id=' + cast(@myInt as varchar(10))
exec (@strSQL)
通过。