All, I have the following dynamic SQL Query
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;
This produces the following error
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.
However, the printed output
IF EXISTS (SELECT *
FROM Report.sys.objects
WHERE name = 'BadCodesErrSumm' AND type = 'U')
DROP TABLE [Report]..[BadCodesErrSumm];
executes fine. What am I missing?
Thanks for your time.
Use
Or
That said, a couple of suggestions: