Syntax check all stored procedures?

前端 未结 9 1945
情话喂你
情话喂你 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 22:55

    I know this is a old question but this is my solution when I could not find any suiting.

    I required to validate my stored procedures and views after alot of changes in the database.

    Basicly what i wanted was to try to do a ALTER PROCEDURE and ALTER VIEW using the current procedures and view (not actually changing them).

    I have written this that works fairly well.

    Note! Do not perform on live database, make a copy to validate and then fix the things need fixing. Also sys.sql_modules can be inconsistent so take extra care. I do not use this to actually make the changes, only to check which are not working properly.

    DECLARE @scripts TABLE
    (
        Name NVARCHAR(MAX),
        Command NVARCHAR(MAX),
        [Type] NVARCHAR(1)
    )
    
    DECLARE @name NVARCHAR(MAX),        -- Name of procedure or view
        @command NVARCHAR(MAX),         -- Command or part of command stored in syscomments
        @type NVARCHAR(1)               -- Procedure or view
    
    INSERT INTO @scripts(Name, Command, [Type])
    SELECT P.name, M.definition, 'P' FROM sys.procedures P 
    JOIN sys.sql_modules M ON P.object_id = M.object_id
    
    INSERT INTO @scripts(Name, Command, [Type])
    SELECT V.name, M.definition, 'V' FROM sys.views V 
    JOIN sys.sql_modules M ON V.object_id = M.object_id
    
    DECLARE curs CURSOR FOR
    SELECT Name, Command, [Type]  FROM @scripts
    
    OPEN curs
    
    FETCH NEXT FROM curs
    INTO @name, @command, @type
    
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
        BEGIN TRY
            IF @type = 'P'
                SET @command = REPLACE(@command, 'CREATE PROCEDURE', 'ALTER PROCEDURE')
            ELSE
                SET @command = REPLACE(@command, 'CREATE VIEW', 'ALTER VIEW')
    
    
            EXEC sp_executesql @command
            PRINT @name + ' - OK'
        END TRY
        BEGIN CATCH
            PRINT @name + ' - FAILED: ' + CAST(ERROR_NUMBER() AS NVARCHAR(MAX)) + ' ' + ERROR_MESSAGE()
            --PRINT @command
        END CATCH
    
        FETCH NEXT FROM curs
        INTO @name, @command, @type
    END
    
    CLOSE curs 
    

提交回复
热议问题