Syntax check all stored procedures?

前端 未结 9 1980
情话喂你
情话喂你 2020-12-04 22:51

i want to ensure that all stored procedures are still syntactically valid. (This can happen if someone renames/deletes a table/column).

Right now my solution to chec

9条回答
  •  盖世英雄少女心
    2020-12-04 23:04

    The check suggested by KenJ is definitely the best one, since the recreate/alter-approaches does not find all errors. E.g.

    • impossible execution plans due to query-hints
    • I even had an SP referencing a non-existing table that went through without the error being detected.

    Please find my version that checks all existing SPs at once with KenJ's method below. AFAIK, it will detect every error that will keep the SP from being executed.

    --Forces the creation of execution-plans for all sps.
    --To achieve this, a temporary SP is created that calls all existing SPs.
    --It seems like the simulation of the parameters is not necessary. That makes things a lot easier.
    DECLARE @stmt NVARCHAR(MAX) = 'CREATE PROCEDURE pTempCompileTest AS ' + CHAR(13) + CHAR(10)
    SELECT @stmt = @stmt + 'EXEC [' + schemas.name + '].[' + procedures.name + '];'
        FROM sys.procedures
            INNER JOIN sys.schemas ON schemas.schema_id = procedures.schema_id
        WHERE schemas.name = 'dbo'
        ORDER BY procedures.name
    
    EXEC sp_executesql @stmt
    GO
    
    --Here, the real magic happens.
    --In order to display as many errors as possible, XACT_ABORT is turned off.
    --Unfortunately, for some errors, the execution stops anyway.
    SET XACT_ABORT OFF
    GO
    --Showplan disables the actual execution, but forces t-sql to create execution-plans for every statement.
    --This is the core of the whole thing!
    SET SHOWPLAN_ALL ON
    GO
    --You cannot use dynamic SQL in here, since sp_executesql will not be executed, but only show the string passed in in the execution-plan
    EXEC pTempCompileTest
    GO
    SET SHOWPLAN_ALL OFF
    GO
    SET XACT_ABORT ON
    GO
    --drop temp sp again
    DROP PROCEDURE pTempCompileTest
    --If you have any errors in the messages-window now, you should fix these...
    

提交回复
热议问题