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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With