我有一张表和这样的值
create table exTABLE(abc int)
insert into exTABLE(abc) values(10)
insert into exTABLE(abc) values(20)
insert into exTABLE(abc) values(30)
我已经创建了一个像这样的存储过程
alter procedure proced
@tablename varchar(max)
as
begin
declare @sql as varchar(max)
set @sql='select max(abc) from '+@tablename
--print @sql
exec(@sql)
end
我将得到的结果为30,这是正确的答案,但我需要将结果选中的30放入存储过程内的单独的int变量中,我需要将其作为输出,即我试图这样做
alter procedure proced
@tablename varchar(max)
as
begin
declare @sql as varchar(max)
set @sql = 'select max(abc) from '+@tablename
--print @sql
exec(@sql)
declare @i as int
set @i = cast(@sql as int)
exec(@i)
print @i
end
我需要将i的打印值设为30。任何替代方法也将非常有用
答案 0 :(得分:2)
将@sql声明为nvarchar并改为使用sp_executesql。传递输入和输出参数以从int变量中的sql语句收集结果。
Alter procedure proced
@tablename varchar(max)
as
begin
declare @sql as nvarchar(max),@i int
, @Param nvarchar(500);
set @sql='select @i1=max(abc) from '+@tablename
SET @Param = N'@i1 int OUTPUT';
EXEC sp_executesql @sql, @Param, @i1=@i OUTPUT;
Print @i
Select @i
end
exec proced 'exTABLE'
答案 1 :(得分:0)
这将打印并返回:
ALTER PROCEDURE proced
@tablename VARCHAR(max)
AS
BEGIN
DECLARE @sql AS VARCHAR(max)
SET @sql='DECLARE @i AS INT; SELECT @i = MAX(abc) FROM '+@tablename + ';PRINT @i; SELECT @i'
exec(@sql)
END