立即删除所有存储过程

时间:2013-01-20 12:42:02

标签: sql stored-procedures sql-server-2008-r2

我的Stored Procedures数据库中有200个Sql server 2008 R2由应用程序自动生成。现在我想删除它们 all 并重新生成它们,因为表格已经发生了很大的变化。

This question is very similar to my case但在我的情况下,所有SP都以 sp _ 开头,我认为使用相同的代码是危险的,因为系统SP也是以 sp _ 我可能全部杀了他们。

我应该相信the link above中的解决方案吗?如果没有,是否有更安全的解决方案?

5 个答案:

答案 0 :(得分:24)

如果这是一次性任务,只需打开对象资源管理器,展开您的数据库>可编程性并突出显示“存储过程”节点。然后打开对象资源管理器详细信息(我认为是F7)。在右边你应该看到你的列表,在这里你可以多选 - 所以你可以按名称排序,选择所有以sp_开头的程序,并通过一次击键将它们全部删除。

如果您反复这样做,那么(假设您的程序都在dbo架构中):

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql += N'DROP PROCEDURE dbo.'
  + QUOTENAME(name) + ';
' FROM sys.procedures
WHERE name LIKE N'sp[_]%'
AND SCHEMA_NAME(schema_id) = N'dbo';

EXEC sp_executesql @sql;

答案 1 :(得分:1)

-- drop all user defined stored procedures

    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 

答案 2 :(得分:0)

我发现了这个How to Drop All Stored Procedures in Your Database然后我进行了测试,StoredProcedure是在 Stored Procedures 文件夹之外创建的。

CREATE PROC UserStoredProcedure_Sample1
 AS
       SELECT 'SQL Server rocks'
  GO

CREATE PROC UserStoredProcedure_Sample2
 AS
     SELECT 'SQL Server rocks'
 GO

 SET NOCOUNT ON

  -- to do this we have to use EXEC instead of sp_executesql
 -- sp_executesql does not accept a DROP command in the SQL String
 DECLARE @UserStoredProcedure    VARCHAR(100)
 DECLARE @Command                    VARCHAR(100)

 DECLARE UserStoredProcedureCursor CURSOR SCROLL STATIC READ_ONLY FOR
 SELECT
     SPECIFIC_NAME
 FROM
    INFORMATION_SCHEMA.ROUTINES

  OPEN UserStoredProcedureCursor

FETCH NEXT FROM UserStoredProcedureCursor
 INTO @UserStoredProcedure
  WHILE (@@FETCH_STATUS = 0) BEGIN
        SET @Command = 'DROP PROCEDURE ' + @UserStoredProcedure

         -- display; visual check
         SELECT @Command

        -- when you are ready to execute, uncomment below
        EXEC (@Command)

        FETCH NEXT FROM UserStoredProcedureCursor
         INTO @UserStoredProcedure
  END


 CLOSE UserStoredProcedureCursor
 DEALLOCATE UserStoredProcedureCursor

   SET NOCOUNT OFF

答案 3 :(得分:0)

DECLARE @DeleteProcCommand NVARCHAR(500)

DECLARE Syntax_Cursor CURSOR
FOR
SELECT 'DROP PROCEDURE ' + p.NAME
FROM sys.procedures p

OPEN Syntax_Cursor

FETCH NEXT FROM Syntax_Cursor

INTO @DeleteProcCommand

WHILE (@@FETCH_STATUS = 0)
BEGIN

EXEC (@DeleteProcCommand)

FETCH NEXT FROM Syntax_Cursor
INTO @DeleteProcCommand

END

CLOSE Syntax_Cursor

DEALLOCATE Syntax_Cursor

答案 4 :(得分:0)

DECLARE @sql VARCHAR(MAX)='';

SELECT @sql=@sql+'drop procedure ['+name +'];' FROM sys.objects 
WHERE type = 'p' AND  is_ms_shipped = 0

exec(@sql);