用表名作为参数,如何获取查询结果.
declare @autoid int
declare @nautoid int
declare @sql nvarchar(2000)
declare @tablename nvarchar(200)
declare @field nvarchar(50)
set @tablename= 'tbl_calendarday '
set @field= 'cid '
set @sql= 'select @nautoid=max( ' + @field + ') from ' + @tablename + ' '
print @sql
exec(@sql)
执行到
set @sql= 'select @nautoid=max( ' + @field + ') from ' + @tablename + ' '
这句就出错了,请问应该如何解决呢?
错误信息:Must declare the variable '@nautoid '.
------解决方案-------------------- declare @autoid int
declare @nautoid int
declare @sql nvarchar(2000)
declare @tablename nvarchar(200)
declare @field nvarchar(50)
set @tablename= 'sysobjects '
set @field= 'id '
set @sql= 'select @autoid=max( ' + @field + ') from ' + @tablename
--print @sql
exec sp_executesql @sql,N '@autoid int output ',@autoid output
print @autoid