The following code does not work, and I am unsure why.
DECLARE @TableName varchar(100)
DECLARE @DBName varchar(50)
DECLARE @FinalTableName varchar(500)
DECLARE @TempDB varchar(50)
SET @DBName=(select db_name())
SET @TableName = 'tbl_Product'
SET @FinalTableName = @DBName + '-' + @TableName +'-' + cast(CONVERT (date, GETDATE()) as varchar(100))
SET @TempDB = 'MiscDB.sys.objects'
Declare @SQL VarChar (250)
Declare @tableExist VarChar (200)
SET @SQL = 'select @tableExist = OBJECT_ID FROM ' + @TempDB + ' WHERE object_id = OBJECT_ID(''' + @TableName + ''') AND type in (N''U'')'
exec @SQL
I get this error
Msg 911, Level 16, State 4, Line 15
Database ‘select @tableExist = OBJECT_ID FROM MiscDB’ does not exist. Make sure that the name is entered correctly.
If I run the SQL statement directly, however, it does work.
Your query should probably be:
If the database name is fixed (you seem to have hard-coded
Misc) it is slightly easier: