表名为变量我正在尝试执行以下查询:declare @tablename varchar(50)set @tablename = 'test'select * from @tablename这会产生以下错误:MSG 1087,16级,状态1,第5行必须声明表变量“@tablename”。动态填充表名的正确方法是什么?
3 回答
喵喵时光机
TA贡献1846条经验 获得超7个赞
红颜莎娜
TA贡献1842条经验 获得超12个赞
EXEC('SELECT * FROM ' + @tablename)
--DECLARE TABLE NAME VARIABLE DYNAMICALLYDECLARE @table_name varchar(max)SET @table_name = (SELECT 'TEST_' + DATENAME(YEAR,GETDATE()) + UPPER(DATENAME(MONTH,GETDATE())) )--DROP THE TABLE IF IT ALREADY EXISTSIF 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 TABLEEXEC('SELECT * INTO ' + @table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')
胡子哥哥
TA贡献1825条经验 获得超6个赞
DECLARE @sqlCommand varchar(1000)SET @sqlCommand = 'SELECT * from yourtable'EXEC (@sqlCommand)
添加回答
举报
0/150
提交
取消