How to drop all stored procedures at once in SQL Server database?

后端 未结 14 2024
囚心锁ツ
囚心锁ツ 2021-01-29 22:53

Currently we use separate a drop statements for each stored procedure in the script file:

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N\'[         


        
14条回答
  •  说谎
    说谎 (楼主)
    2021-01-29 23:16

    ANSI compliant, without cursor

    DECLARE @SQL national character varying(MAX) 
    SET @SQL= ''
    
    SELECT @SQL= @SQL+ N'DROP PROCEDURE "' + REPLACE(SPECIFIC_SCHEMA, N'"', N'""') + N'"."' + REPLACE(SPECIFIC_NAME, N'"', N'""') + N'"; '
    FROM INFORMATION_SCHEMA.ROUTINES 
    
    WHERE (1=1) 
    AND ROUTINE_TYPE = 'PROCEDURE' 
    AND ROUTINE_NAME NOT IN 
    (
         'dt_adduserobject'
        ,'dt_droppropertiesbyid'
        ,'dt_dropuserobjectbyid'
        ,'dt_generateansiname'
        ,'dt_getobjwithprop'
        ,'dt_getobjwithprop_u'
        ,'dt_getpropertiesbyid'
        ,'dt_getpropertiesbyid_u'
        ,'dt_setpropertybyid'
        ,'dt_setpropertybyid_u'
        ,'dt_verstamp006'
        ,'dt_verstamp007'
    
        ,'sp_helpdiagrams'
        ,'sp_creatediagram'
        ,'sp_alterdiagram'
        ,'sp_renamediagram'
        ,'sp_dropdiagram'
    
        ,'sp_helpdiagramdefinition'
        ,'fn_diagramobjects'
        ,'sp_upgraddiagrams'
    ) 
    
    
    ORDER BY SPECIFIC_NAME 
    
    
    -- PRINT @SQL
    EXEC(@SQL) 
    

    Without cursor, non-ansi compliant:

    DECLARE @sql NVARCHAR(MAX) = N''
    , @lineFeed NVARCHAR(2) = CHAR(13) + CHAR(10) ;
    
    SELECT @sql = @sql + N'DROP PROCEDURE ' + QUOTENAME(SPECIFIC_SCHEMA) + N'.' + QUOTENAME(SPECIFIC_NAME) + N';' + @lineFeed
    FROM INFORMATION_SCHEMA.ROUTINES 
    WHERE ROUTINE_TYPE = 'PROCEDURE' 
    -- AND SPECIFIC_NAME LIKE 'sp[_]RPT[_]%'
    
    
    AND ROUTINE_NAME NOT IN 
    ( 
        SELECT name FROM sys.procedures WHERE is_ms_shipped <> 0 
    ) 
    
    
    ORDER BY SPECIFIC_NAME 
    
    
    -- PRINT @sql 
    EXECUTE(@sql)
    

提交回复
热议问题