2011-02-11 94 views
3

我想创建一些动态选择基于发送到数据库的ID运行的过程的表的方法。例如:SQL表选择

@TableId int 
As 

Declare @nameoftable varchar(50) 

select @nameoftable = Nameoftable from tablelist where id = @tableid 


-- returning on selected table 

Select somestuff 
from @nameoftable 

任何想法?

回答

3

你需要使用动态SQL

@TableId int 
As 

Declare @nameoftable varchar(50) 
select @nameoftable = Nameoftable from tablelist where id = @tableid 

-- returning on selected table 

declare @sql nvarchar(1000) 
set @sql = 'Select somestuff from ' + Quotename(@nameoftable) 
exec(@sql) 
+0

我试图避免只是执行一个sql片段,只是从@nameoftable返回值。有没有其他方式做到这一点? – Drakullmonkey 2011-02-11 11:00:03