表名称作为variables

我正在尝试执行此查询:

declare @tablename varchar(50) set @tablename = 'test' select * from @tablename 

这会产生以下错误:

Msg 1087,Level 16,State 1,Line 5

必须声明表variables“@tablename”。

什么是dynamic填充表名称的正确方法?

如果查询是静态的,则表名称和列名称必须是静态的。 对于dynamic表或列名称,应该dynamic生成完整的SQL,并使用sp_executesql执行它。

更多细节在这里: dynamicSQL的诅咒和祝福

改变你的最后陈述:

 EXEC('SELECT * FROM ' + @tablename) 

这是我在一个存储过程中如何做到的。 第一个块将声明variables,并根据当前的年份和月份名称设置表名,在这种情况下为TEST_2012OCTOBER。 然后我检查它是否已经存在于数据库中,并删除它。 然后下一个块将使用一个SELECT INTO语句来创build该表,并用另一个带有参数的表中的logging填充它。

 --DECLARE TABLE NAME VARIABLE DYNAMICALLY DECLARE @table_name varchar(max) SET @table_name = (SELECT 'TEST_' + DATENAME(YEAR,GETDATE()) + UPPER(DATENAME(MONTH,GETDATE())) ) --DROP THE TABLE IF IT ALREADY EXISTS IF EXISTS(SELECT name FROM sysobjects WHERE name = @table_name AND xtype = 'U') BEGIN EXEC('drop table ' + @table_name) END --CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE EXEC('SELECT * INTO ' + @table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''') 

你不能为一个variables使用表名,你必须这样做:

 DECLARE @sqlCommand varchar(1000) SET @sqlCommand = 'SELECT * from yourtable' EXEC (@sqlCommand) 

有点晚回答,但应该帮助别人:

 CREATE PROCEDURE [dbo].[GetByName] @TableName NVARCHAR(100) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @sSQL nvarchar(500); SELECT @sSQL = N'SELECT * FROM' + QUOTENAME(@TableName); EXEC sp_executesql @sSQL END 

你需要dynamic生成sql:

 declare @tablename varchar(50) set @tablename = 'test' declare @sql varchar(500) set @sql = 'select * from ' + @tablename exec (@sql) 
 Declare @fs_e int, @C_Tables CURSOR, @Table varchar(50) SET @C_Tables = CURSOR FOR select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%' OPEN @C_Tables FETCH @C_Tables INTO @Table SELECT @fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '@C_Tables' WHILE ( @fs_e <> -1) BEGIN exec('Select * from '+ @Table) FETCH @C_Tables INTO @Table SELECT @fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '@C_Tables' END 
 DECLARE @tbl sysname, @sql nvarchar(4000), @params nvarchar(4000), @count int DECLARE tblcur CURSOR STATIC LOCAL FOR SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated' ORDER BY 1 OPEN tblcur WHILE 1 = 1 BEGIN FETCH tblcur INTO @tbl IF @@fetch_status <> 0 BREAK SELECT @sql = N' SELECT @cnt = COUNT(*) FROM dbo.' + quotename(@tbl) + N' WHERE LastUpdated BETWEEN @fromdate AND ' + N' coalesce(@todate, ''99991231'')' SELECT @params = N'@fromdate datetime, ' + N'@todate datetime = NULL, ' + N'@cnt int OUTPUT' EXEC sp_executesql @sql, @params, '20060101', @cnt = @count OUTPUT PRINT @tbl + ': ' + convert(varchar(10), @count) + ' modified rows.' END DEALLOCATE tblcur 

我已经把这些线