DECLARE @Objects TABLE
(
OID INT NOT NULL PRIMARY KEY IDENTITY(1,1)
, FQN NVARCHAR(256) NOT NULL
, IsIssue BIT NOT NULL DEFAULT (CONVERT(BIT, 0))
)
DECLARE @SQLCommand NVARCHAR(4000)
DECLARE @VName NVARCHAR(256)
DECLARE @OID INT
INSERT INTO @Objects
(FQN)
SELECT QUOTENAME(S.name) + '.' + QUOTENAME(V.name)
FROM sys.views AS V
INNER JOIN sys.schemas AS S ON S.Schema_id = V.schema_id
DECLARE curLoop CURSOR LOCAL STATIC FORWARD_ONLY
FOR SELECT OID, FQN
FROM @Objects AS O
OPEN curLoop
FETCH NEXT FROM curLoop
INTO @OID, @VName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQLCommand = N'EXEC sp_refreshview N' + QUOTENAME(@VName, '''')
BEGIN TRY
EXEC sp_executesql @SQLCommand
END TRY
BEGIN CATCH
UPDATE @Objects
SET IsIssue = 1
WHERE OID = @OID
END CATCH
FETCH NEXT FROM curLoop
INTO @OID, @VName
END
CLOSE curLoop
DEALLOCATE curLoop
SELECT OID, FQN, IsIssue
FROM @Objects
WHERE IsIssue = 1
您可以使用 sp_refreshview 来完成它。我将这个小脚本放在一起,它将选择数据库中的所有视图,对其运行 sp_refreshview 并告诉您哪些有问题。
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-refreshview-transact-sql?view=sql-server-2017