9

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

这个问题与我的情况非常相似,但在我的情况下,所有 SP 都以sp_ 开头,我认为使用相同的代码很危险,因为系统 SP 也以sp_ 开头,我可能会全部杀死它们。

我应该相信上面链接中的解决方案吗?如果没有,有没有更安全的解决方案?

4

5 回答 5

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;
于 2013-01-20T13:06:10.633 回答
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 
于 2016-07-13T04:57:27.983 回答
0

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

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
于 2013-01-20T13:10:20.187 回答
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
于 2013-08-21T11:25:19.567 回答
0
DECLARE @sql VARCHAR(MAX)='';

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

exec(@sql);
于 2016-02-11T12:21:43.657 回答