带变量的sql语句,要返回一个结果时,怎么样的到结果?

来源:百度知道 编辑:UC知道 时间:2024/05/12 10:54:37
一般是这样的
declare @id int
select @id=stuId from stuInfo
print @id

现在不确定表名,用一个变量代替
declare @id int
declare @tabName varchar(20)
select @id=stuId from @tabName
print @id

这样就不对了,应该怎么写?
我要把执行的sql语句得到的值给变量,好做其他事情,光执行sql语句不行

如果要使用得到的变量,可以用一个临时表#tmp保存,用完要记得删表。

declare @id int
declare @tabName varchar(20)
declare @sql varchar(255)
set @sql = 'select stuId into #tmp from '+@tabName
exec(@sql)
select @id=stuId from #tmp
drop table #tmp
print @id

不允许表名为变量, 不知道2005可以不,没用过