1

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

执行良好。我错过了什么?

谢谢你的时间。

4

1 回答 1

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;
于 2012-07-19T15:25:22.480 回答