奇怪的动态SQL错误

时间:2012-07-19 15:23:16

标签: sql sql-server-2008 dynamic-sql

全部,我有以下动态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;

这会产生以下错误

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.

然而,打印输出

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

执行得很好。 我缺少什么?

感谢您的时间。

1 个答案:

答案 0 :(得分:5)

使用

EXEC sp_executesql @DropSql;

或者

EXEC(@DropSql);

那说,有几点建议:

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;