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

后端 未结 14 2022
囚心锁ツ
囚心锁ツ 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:38

    By mixing the cursor and system procedure, we would have a optimized solution, as follow:

    DECLARE DelAllProcedures CURSOR
    FOR
        SELECT name AS procedure_name 
        FROM sys.procedures;
    OPEN DelAllProcedures
    DECLARE @ProcName VARCHAR(100)
    FETCH NEXT 
    FROM DelAllProcedures
    INTO @ProcName
    WHILE @@FETCH_STATUS!=-1
    BEGIN 
        DECLARE @command VARCHAR(100)
        SET @command=''
        SET @command=@command+'DROP PROCEDURE '+@ProcName
        --DROP PROCEDURE  @ProcName
        EXECUTE (@command)
        FETCH NEXT 
        FROM DelAllProcedures
        INTO @ProcName
    END
    CLOSE DelAllProcedures
    DEALLOCATE DelAllProcedures
    
    0 讨论(0)
  • 2021-01-29 23:41

    Try this, it work for me

    DECLARE @spname sysname;
    DECLARE SPCursor CURSOR FOR
    SELECT SCHEMA_NAME(schema_id) + '.' + name
    FROM sys.objects
    WHERE type = 'P';
    OPEN SPCursor;
    FETCH NEXT FROM SPCursor INTO @spname;
    WHILE @@FETCH_STATUS = 0
    BEGIN
    EXEC('DROP PROCEDURE ' + @spname);
    FETCH NEXT FROM SPCursor INTO @spname;
    END
    CLOSE SPCursor;
    DEALLOCATE SPCursor;
    
    0 讨论(0)
提交回复
热议问题