如何查找在数据库中执行时出错的所有视图或存储过程的列表?
有时用户在视图中进行更改(删除视图中的特定字段)而不检查其依赖性。然后,使用视图的所有相关视图和存储过程都会出错,XXX列缺失。 是否有任何特定的脚本来检查在执行时出错的所有视图和存储过程列表。
答案 0 :(得分:2)
这是我用来验证视图元数据并刷新它以获取任何架构或查看更改的脚本......这可能适合您:
-- Refresh the metadata for all views in the 'dbo' schema
SET NOCOUNT ON
DECLARE @viewName AS VARCHAR(255)
DECLARE @count int
DECLARE listOfViews CURSOR FOR
SELECT [TABLE_NAME]
FROM INFORMATION_SCHEMA.VIEWS v
LEFT OUTER JOIN sys.sql_dependencies d ON v.[TABLE_NAME] = OBJECT_NAME(d.object_id)
WHERE [TABLE_SCHEMA] = 'dbo' AND
(d.[class_desc] IS NULL OR d.[class_desc] <> 'OBJECT_OR_COLUMN_REFERENCE_SCHEMA_BOUND')
GROUP BY [TABLE_NAME]
ORDER BY [TABLE_NAME]
OPEN listOfViews
FETCH NEXT FROM listOfViews into @viewName
SET @count = 0
WHILE (@@FETCH_STATUS <> -1)
BEGIN
BEGIN TRY
EXEC sp_refreshview @viewName
END TRY
BEGIN CATCH
IF XACT_STATE() = -1 ROLLBACK
PRINT @viewName + ' has ERRORS: ' + ERROR_MESSAGE()
SET @count = @count + 1
END CATCH
FETCH NEXT FROM listOfViews INTO @viewName
END
CLOSE listOfViews
DEALLOCATE listOfViews
PRINT 'Total Views with errors: ' + CAST(@count AS nvarchar(10))
SET NOCOUNT OFF