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

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

    ANSI compliant, without cursor

    PRINT ('1.a. Delete stored procedures ' + CONVERT( VARCHAR(19), GETDATE(), 121));
    GO
    DECLARE @procedure NVARCHAR(max)
    DECLARE @n CHAR(1)
    SET @n = CHAR(10)
    SELECT @procedure = isnull( @procedure + @n, '' ) +
    'DROP PROCEDURE [' + schema_name(schema_id) + '].[' + name + ']'
    FROM sys.procedures
    
    EXEC sp_executesql @procedure
    PRINT ('1.b. Stored procedures deleted ' + CONVERT( VARCHAR(19), GETDATE(), 121));
    GO
    
    0 讨论(0)
  • 2021-01-29 23:32

    I think this is the simplest way:

    DECLARE @sql VARCHAR(MAX)='';
    
    SELECT @sql=@sql+'drop procedure ['+name +'];' FROM sys.objects 
    WHERE type = 'p' AND  is_ms_shipped = 0
    
    exec(@sql);
    
    0 讨论(0)
  • 2021-01-29 23:33

    To get drop statements for all stored procedures in a database SELECT 'DROP PROCEDURE' + ' ' + F.NAME + ';' FROM SYS.objects AS F where type='P'

    0 讨论(0)
  • 2021-01-29 23:34

    Something like (Found at Delete All Procedures from a database using a Stored procedure in SQL Server).

    Just so by the way, this seems like a VERY dangerous thing to do, just a thought...

    declare @procName varchar(500)
    declare cur cursor 
    
    for select [name] from sys.objects where type = 'p'
    open cur
    fetch next from cur into @procName
    while @@fetch_status = 0
    begin
        exec('drop procedure [' + @procName + ']')
        fetch next from cur into @procName
    end
    close cur
    deallocate cur
    
    0 讨论(0)
  • 2021-01-29 23:35
    DECLARE @sql VARCHAR(MAX)
    SET @sql=''
    SELECT @sql=@sql+'drop procedure ['+name +'];' FROM sys.objects
    WHERE type = 'p' AND  is_ms_shipped = 0
    exec(@sql);
    
    0 讨论(0)
  • 2021-01-29 23:37

    Try this:

    DECLARE @sql NVARCHAR(MAX) = N'';
    
    SELECT @sql += N'DROP PROCEDURE dbo.'
      + QUOTENAME(name) + ';
    ' FROM sys.procedures
    WHERE name LIKE N'spname%'
    AND SCHEMA_NAME(schema_id) = N'dbo';
    
    EXEC sp_executesql @sql;
    
    0 讨论(0)
提交回复
热议问题