Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do SQL Server Views needs to be refreshed every once in a while

Why do I have to write 'refresh view' scripts, and execute them every time I add or edit some fields to a view?

SQL Server understands that it needs to refresh the view when editing it in the fancy view-edit windows in Management Studio, so why can't it just tell its view to go refresh itself after editing the view through a script?

like image 604
Jan Jongboom Avatar asked Aug 13 '09 15:08

Jan Jongboom


1 Answers

I had the same problem with table changes. The real solution is a DDL trigger for alter table:

Create Trigger RefreshViewTrigger On Database FOr Alter_Table As
Declare @tname as nvarchar(256), @sql nvarchar(400);
Select @tname = EVENTDATA().value('(/EVENT_INSTANCE/SchemaName)[1]','nvarchar(100)')  + '.' +  EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]','nvarchar(100)');
Declare k cursor For Select distinct 'sp_refreshview ''' + o.name + '''' sql
    From sys.objects o Join sys.sql_expression_dependencies s On o.object_id = s.referencing_id   
    Where o.type = 'V' AND s.referenced_id = Object_id(@tname);  
Open k
Fetch Next from k into @sql
While @@FETCH_STATUS = 0
Begin
    Print( @sql )
    EXEC( @sql )
    Fetch Next from k into @sql
End
Close k
Deallocate k
Go

I works on 2008 R2, maybe even earlier versions.

like image 105
Peter Krassoi Avatar answered Sep 25 '22 10:09

Peter Krassoi