How to execute all views in a database using a stored procedure

We have a problem with the fact that our table schema is not synchronized with our view schema. I would like to know how I can have a stored procedure (for Sql Server) that gets all the views in the database and executes each of them with select *

Here is what I introduced (pseudo):


Declare x
Set x = Select an object from sysobjects, where object = view

view foreach in x
sp_execute 'select * from view'


Then we could get an automated test that calls it every night. A SqlException indicates that something is out of sync.

+3
source share
3 answers

supposed to work in 2000 and

select quotename(table_schema) +'.' + quotename(table_name) as ViewNAme,
 identity(int,1,1) as ID
  into #test
  from information_schema.tables
 where table_type = 'view'


declare @Loopid int,@MaxID int


select @LoopID =1,@MaxID =MAX(id) 
from #test

declare @ViewName varchar(100)

while @LoopID <= @MaxID
begin

select @ViewName = ViewNAme 
from #test
where id = @LoopID

exec ('select top 1 * from ' + @ViewName)
set @LoopID = @LoopID + 1
end

drop table #test

I mainly focus on one part of your question, see also how to make sure that the view will have base table changes using sp_refreshview

+4
source

I really suggest you use WITH SCHEMABINDING to prevent this from happening.

Or use sp_refreshview in a loop at least.

SELECT * FROM view not reliable: how do you know if the result is correct or not?

+2
source

In SQL 2008, you can use the following to detect unresolved dependencies without actually choosing from a view.

SELECT * 
FROM sys.views v
JOIN sys.sql_expression_dependencies e ON e.referencing_id = v.object_id
and  referenced_id is null
0
source

Source: https://habr.com/ru/post/1760789/


All Articles