I have some SQL code that needs to be executed if a certain View exists in a database. How would I go about checking if the View exists?
EDIT: The DBMS being used is Mic
If you want to check the validity and consistency of all the existing views you can use the following query
declare @viewName sysname
declare @cmd sysname
DECLARE check_cursor CURSOR FOR
SELECT cast('['+SCHEMA_NAME(schema_id)+'].['+name+']' as sysname) AS viewname
FROM sys.views
OPEN check_cursor
FETCH NEXT FROM check_cursor
INTO @viewName
WHILE @@FETCH_STATUS = 0
BEGIN
set @cmd='select * from '+@viewName
begin try
exec (@cmd)
end try
begin catch
print 'Error: The view '+@viewName+' is corrupted .'
end catch
FETCH NEXT FROM check_cursor
INTO @viewName
END
CLOSE check_cursor;
DEALLOCATE check_cursor;