使用变量作为表名失败

时间:2015-11-11 13:25:48

标签: sql sql-server tsql execute

为什么会因以下错误消息而失败:

  

Msg 102,Level 15,State 1,Line 1   " reporting_rawdata_v2'附近的语法不正确。

表的名称是" dbo.reporting_rawdata_v2"但是有没有" dbo"它仍然失败......

Use reporting2 
Go

Declare @Backupdate varchar(25), @sql NVARCHAR(max)
Set @Backupdate = REPLACE(REPLACE(CAST(CONVERT(VARCHAR(20), SYSDATETIME(), 100) as varchar),' ','_'),':', '')
Select @Backupdate

SET @sql = 'Select * Into reporting_rawdata_BACKUP_' + @Backupdate + 'From reporting_rawdata_v2';
EXEC (@sql);

1 个答案:

答案 0 :(得分:2)

动态命名的表与From

之间没有空格
SET @sql = 'Select * Into reporting_rawdata_BACKUP_' + @Backupdate + ' From reporting_rawdata_v2';
EXEC (@sql);