用游标:declare #tb cursor for select .. --将select的数据集定义为游标 open #tb --打开游标 fetch next from #tb into @变量列表 --从游标中循环取数,并放到变量中 while @@fetch_status=0 --如果取数成功 begin --进行数据处理 print @变量 --数据处理语句 fetch next from #tb into @变量列表 --继续取数 end close #tb --关闭游标 deallocate #tb --释放游标
如果只是得到bookid,可以用下面的方法:declare @sql nvarchar(4000),@bookid int set @sql='select @bookid=bookid from book_' + @num + ' where bookname=''aa''' exec sp_executesql @sql,N'@bookid int output',@bookid output
declare @bookid int declare @ss nvarchar(1000)set @ss=N'select @bookid = bookid from book_' + @num + ' where bookname=''aa'''exec sp_executesql @ss ,N'@bookid int output',@bookid output
open #tb --打开游标
fetch next from #tb into @变量列表 --从游标中循环取数,并放到变量中
while @@fetch_status=0 --如果取数成功
begin --进行数据处理
print @变量 --数据处理语句
fetch next from #tb into @变量列表 --继续取数
end
close #tb --关闭游标
deallocate #tb --释放游标
set @sql='select @bookid=bookid from book_' + @num + ' where bookname=''aa'''
exec sp_executesql @sql,N'@bookid int output',@bookid output
这样会不会涉及到性能问题