Unanswered: SQL Server: How do I ignore errors on a view creation?
I have a sql script which creates a view. This view references a table that does not exist when the view is created. So, it throws an error. I am wondering how I can catch the error and allow the view to be created anyway with no error thrown (important). I have tried wrapping it in a try catch, but it seems that is not allowed. I have tried using an if (@@error <> 0) statement, but it doesn't stop the error from being thrown.
I just want to prevent the error from being returned at all. I have also found that Oracle has exactly what I want (CREATE FORCE VIEW), but that is not available in SQL Server.
Why are you creating a view on a table that does not exist?
The easy way to do it is temporarily create the table before you create the view then drop it afterwards.
-- If The table doesn't exists, create it.
If Not Exists (Select 1 From Information_Schema.Tables Where Table_Name = 'TestTable')
Create Table TestTable (Col1 int primary key)
-- If the view already exists, drop it first.
If Exists (Select 1 From Information_Schema.Views Where Table_Name = 'TestView')
Drop View TestView
-- Create the view.
Create View TestView
Select Col1 From TestTable
--Drop the table
Drop Table TestTable
I would suggest you either create the dependent objects AFTER the base objects (radical thought, I know), or create the view as a stub with no table references, and then ALTER the view at the end of the install.
If it's not practically useful, then it's practically useless.