奇怪的动态SQL错误

Moo*_*ght 1 sql dynamic-sql sql-server-2008

全部,我有以下动态SQL查询

DECLARE @TableName NVARCHAR(255);
SET @TableName = 'BadCodesErrSumm';
DECLARE @DropSql NVARCHAR(MAX);
SET @DropSql = 
    'IF EXISTS (SELECT *  
                FROM Report.sys.objects 
                WHERE name = ''' + @TableName + ''' AND type = ''U'') 
     DROP TABLE [IPAReport]..[' + @TableName + '];'
PRINT @DropSql;
EXEC @DropSql;
Run Code Online (Sandbox Code Playgroud)

这会产生以下错误

Msg 203, Level 16, State 2, Line 11
The name 'IF EXISTS (SELECT *  
                FROM Report.sys.objects 
                WHERE name = 'BadCodesErrSumm' AND type = 'U') 
          DROP TABLE [Report]..[BadCodesErrSumm];' is not a valid identifier.
Run Code Online (Sandbox Code Playgroud)

但是,打印输出

IF EXISTS (SELECT *  
           FROM Report.sys.objects 
           WHERE name = 'BadCodesErrSumm' AND type = 'U') 
DROP TABLE [Report]..[BadCodesErrSumm];
Run Code Online (Sandbox Code Playgroud)

执行得很好.我错过了什么?

谢谢你的时间.

Aar*_*and 5

使用

EXEC sp_executesql @DropSql;
Run Code Online (Sandbox Code Playgroud)

要么

EXEC(@DropSql);
Run Code Online (Sandbox Code Playgroud)

那说,有几点建议:

DECLARE @TableName NVARCHAR(255);

SET @TableName = N'BadCodesErrSumm';      -- always use N prefix on Unicode strings

DECLARE @DropSql NVARCHAR(MAX);

SET @DropSql = N'IF EXISTS (SELECT 1      -- again, N prefix
                FROM IPAReport.sys.tables -- use sys.tables to avoid 'U' check
                WHERE name = @TableName)  -- use a proper parameter
     DROP TABLE [IPAReport]..' 
       + QUOTENAME(@TableName) + ';'      -- QUOTENAME is safer as @GSerg pointed out

PRINT @DropSql;

EXEC sp_executesql @DropSql, N'@TableName NVARCHAR(255)', @TableName;
Run Code Online (Sandbox Code Playgroud)