views:

50

answers:

3

We have a problem with our table schema falling out of sync with our view schema. I would like to know how I could have a stored procedure (for Sql Server) that gets all views in the database, and executes each one via select *

Here is what I imagined (pseudo):


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

foreach view in x
sp_execute 'select * from view'


We could then have an automated test that calls this every night. A SqlException would indicated that something was out of sync.

+3  A: 

should work in 2000 and up

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 mostly focused on one part of your question, see also how to make sure that the view will have the underlying table changes by using sp_refreshview

SQLMenace
perfect - thanks
PAR
Not reliable though, is it...?
gbn
I specifically answered this part " I would like to know how I could have a stored procedure (for Sql Server) that gets all views in the database, and executes each one via select *"
SQLMenace
@SQLMenace: Does it solve the problem? Should we not educate and improve?
gbn
Okay..added the refresh view link
SQLMenace
Please throw a TOP 1 into that dynamic SQL :)
Emtucifor
A: 

In SQL 2008 you can use the following to detect unresolved dependencies without having to actually select from the view.

SELECT * 
FROM sys.views v
JOIN sys.sql_expression_dependencies e ON e.referencing_id = v.object_id
and  referenced_id is null
Martin Smith
Created table with 1 field, created view for selecting that field, renamed field in table, executed your query, got an empty result set - not sure what this is supposed to do...The accepted solution gives me the exception I am looking for.
PAR
@PAR - Yes this will get dropped tables. Just looking to see if it can be adjusted for dropped columns also. In any event `sp_refreshview` will get those without having to select everything
Martin Smith
+2  A: 

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

Or use sp_refreshview in a loop at least.

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

gbn