0

Is it possible in SQL Server to check whether table exists in this way? If it doesn't exists, it will run catch

             declare @SQL  varchar(4444)

             select @SQL = '
             begin try
                select * from ServerName.DBName.dbo.TableNAme
             end try
             begin catch
                select 1
             end catch'

             exec (@SQL)

I don't want to use solution described here , because I want to use exact same structure of table as above.

Reason: I will run several dynamic queries in loop, and above ServerName, DbName ,TableName gonna be passed as a parameter.

rakamakafo
  • 1,144
  • 5
  • 21
  • 44

1 Answers1

5

It should work if you do it dynamically. When you don't do it dynamically, the missing table will be caught at parse time, and the CATCH will not be triggered.

EDIT: I mean like this:

         declare @SQL  varchar(4444)

         select @SQL = 'select * from ServerName.DBName.dbo.TableNAme'
         begin try
            exec (@SQL)
         end try
         begin catch
            select 1
         end catch
Tab Alleman
  • 31,483
  • 7
  • 36
  • 52