Find broken objects in SQL Server

前端 未结 11 559
孤独总比滥情好
孤独总比滥情好 2020-12-02 17:26

Is there a tool that will find all objects in SQL Server (functions, procs, views) that cannot possibly work because they refer to objects that don\'t exist?

11条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 18:06

    I wrote a script some years ago that will find Stored Procedures that won't compile by pulling the text of the proc and attempting to recompile it with a try/catch block. It's pretty simple and effective at finding at least procedures that can be dropped. You could easily expand it for views.

    Note that you should only run this against a DEV or TEST environment since it's actually attempting to recompile the procedures.

    SET NOCOUNT ON
    
    DECLARE @ProcedureName VARCHAR(2048)
    DECLARE @ProcedureBody VARCHAR(MAX)
    
    DECLARE @RoutineName varchar(500)
    
    DECLARE procCursor CURSOR STATIC FORWARD_ONLY READ_ONLY
     FOR
     SELECT
     --TOP 1
     SCHEMA_NAME(schema_id) + '.' + NAME AS ProcedureName,
     OBJECT_DEFINITION(o.[object_id]) AS ProcedureBody
     FROM sys.objects AS o
     WHERE o.[type] = 'P'
     ORDER BY o.[name]
    
    OPEN procCursor
    FETCH NEXT FROM procCursor INTO @ProcedureName, @ProcedureBody
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
     -- Might have to play with this logic if you don't have discipline in your create statements
     SET @ProcedureBody = REPLACE(@ProcedureBody, 'CREATE PROCEDURE', 'ALTER PROCEDURE')
    
     BEGIN TRY
       EXECUTE(@ProcedureBody)
       PRINT @ProcedureName + ' -- Succeeded'
     END TRY
     BEGIN CATCH
       PRINT @ProcedureName + ' -- Failed: ' + ERROR_MESSAGE()
     END CATCH
    
     FETCH NEXT FROM procCursor INTO @ProcedureName, @ProcedureBody
    END
    
    CLOSE procCursor
    DEALLOCATE procCursor
    

    https://brettwgreen.wordpress.com/2012/12/04/find-stored-procedures-that-wont-compile/

提交回复
热议问题