Syntax check all stored procedures?

前端 未结 9 1916
情话喂你
情话喂你 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:05

    You can also do this "in-place" - without getting all the create statements.

    In addition to setting NOEXEC ON, you will also need to set your favorite SHOWPLAN_* ON (I use SHOWPLAN_TEXT). Now you can get rid of your step 2 and just execute each procedure you retrieved in step 1.

    Here is a sample using an individual stored procedure. You can work it into your favorite loop:

    create procedure tests @bob int as 
    select * from missing_table_or_view
    go 
    
    set showplan_text on; 
    go 
    
    set noexec on 
    
    exec tests 
    
    set noexec off
    go 
    set showplan_text off; 
    go 
    drop procedure tests 
    go
    

    The above sample should generate the following output:

    Msg 208, Level 16, State 1, Procedure tests, Line 2
    Invalid object name 'missing_table_or_view'.

    0 讨论(0)
  • 2020-12-04 23:07

    There is no way to do it from T-SQL, or Enterprise Manager, so i had to write something from client code. i won't post all the code here, but the trick is to:

    1) Get a list of all stored procedures

     SELECT ROUTINE_NAME AS StoredProcedureName
     FROM INFORMATION_SCHEMA.ROUTINES
     WHERE ROUTINE_TYPE = 'PROCEDURE' --as opposed to a function
     ORDER BY ROUTINE_NAME
    

    2) Get the stored procedure create T-SQL:

    select
       c.text
    from dbo.syscomments c
    where c.id = object_id(N'StoredProcedureName')
    order by c.number, c.colid
    option(robust plan)
    

    3) Run the create statement with NOEXEC on, so that the syntax is checked, but it doesn't actually try to create the stored procedure:

    connection("SET NOEXEC ON", ExecuteNoRecords);
    connection(StoredProcedureCreateSQL, ExecuteNoRecords);
    connection("SET NOEXEC ON", ExecuteNoRecords);
    
    0 讨论(0)
  • 2020-12-04 23:18

    If you are using sql 2008 r2 or below then do not use

    SET NOEXEC ON

    It only checks the syntax and not for potential errors like the existence of tables or columns. Instead use:

    SET FMTONLY ON

    it will do a full compile as it tries to return the meta data of the stored procedure.

    For 2012 and you will need to use stored procedure: sp_describe_first_result_set

    Also you can do a complete script in Tsql that checks all sp and views, its just a bit of work.

    UPDATE I wrote a complete solution for in tsql that goes through all user defined stored proceedures and checks there syntax. the script is long winded but can be found here http://chocosmith.wordpress.com/2012/12/07/tsql-recompile-all-views-and-stored-proceedures-and-check-for-error/

    0 讨论(0)
提交回复
热议问题