Strukturänderungen (Löschen, Einfügen, Ändern von Felder) an Tabelle1 bringen die
View durcheinander.
Dann muss man die Views
refreshen.
Dazu folgende stored procedure:
SQL-Code:
CREATE PROCEDURE spRefreshAllViews
(
@TableName nvarchar(128) = NULL,
@OwnerName nvarchar(128) = NULL
)
AS
/*
Aktualisiert alle von einer Tabelle abhängigen Sichten
der aktuellen Datenbank via sp_refreshview
*/
DECLARE
@cViewName nvarchar(128),
@cOwnerName nvarchar(128),
@fullname nvarchar(256),
@msg nvarchar(255)
SET NOCOUNT ON
IF @TableName IS NULL
SELECT @TableName = '%'
IF @OwnerName IS NULL
SELECT @OwnerName = USER_NAME()
DECLARE curViews CURSOR FOR
SELECT DISTINCT VIEW_SCHEMA, VIEW_NAME
FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE
WHERE TABLE_SCHEMA LIKE @OwnerName AND TABLE_NAME LIKE @TableName
OPEN curViews
FETCH NEXT FROM curViews INTO @cOwnerName, @cViewName
WHILE (@@fetch_status <> -1)
BEGIN
IF (@@fetch_status <> -2)
BEGIN
SELECT @fullname = quotename(@cOwnerName) + '.' +
quotename(@cViewName)
PRINT @fullname
EXEC ('sp_refreshview ' + '''' + @fullname + '''')
END
FETCH NEXT FROM curViews INTO @cOwnerName, @cViewName
END
CLOSE curViews
DEALLOCATE curViews
RETURN 0
GO
Du könntest deine View auch mit dem Attribut SCHEMABINDING versehen,
um Strukturänderungen zu blockieren:
SQL-Code:
CREATE VIEW [ < database_name > . ] [ < owner > . ] view_name [ ( column [ ,...n ] ) ]
WITH SCHEMABINDING
AS ...