如何编辑存储过程?

时间:2015-03-10 10:01:12

标签: sql-server tsql stored-procedures

我的数据库中有几个存储过程,结构如下:

CREATE PROCEDURE MyProcedure (.....)
AS
    DECLARE @myvar NVARCHAR(100);
    SET @myvar = (SELECT .... FROM my_table WHERE ....)
GO

我被要求将my_table子句中的表FROM替换为每个具有它的过程中的另一个。{/ p>

我经历了很多研究,但是我应该创建一个单独运行的脚本,而且我还没有找到合适的东西。例如,我发现sp_helpTetx显示了存储过程的源代码,但有没有办法将其放入变量中进行编辑?

4 个答案:

答案 0 :(得分:1)

您可以使用REDGATE SqlRefactor之类的工具,它可以完美地运行,或者您可以编写所有存储过程的脚本,用ALTER替换CREATE命令,然后在您需要的文本中应用其他REPLACE ...

我做了很多时间,你必须注意,但它有效...

答案 1 :(得分:0)

  1. 使用对该表的引用查找所有存储过程(您可以使用SQL Server中内置的依赖项内容或运行查询该表名的查询,请参阅Search text in stored procedure in SQL Server

  2. 使用" ALTER"编写脚本。而不是" CREATE"按CTRL-H(查找并替换)

  3. 执行脚本。

答案 2 :(得分:0)

这篇文章概述了如何使用游标处理它,以及如上所述的sp_HelpText(包括如上所述的set)。

http://www.ideosity.com/ourblog/post/ideosphere-blog/2013/06/14/how-to-find-and-replace-text-in-all-stored-procedures

-- set "Result to Text" mode by pressing Ctrl+T
SET NOCOUNT ON

DECLARE @sqlToRun VARCHAR(1000), @searchFor VARCHAR(100), @replaceWith     VARCHAR(100)

-- text to search for
SET @searchFor = '[MY-SERVER]'
-- text to replace with
SET @replaceWith = '[MY-SERVER2]'

-- this will hold stored procedures text
DECLARE @temp TABLE (spText VARCHAR(MAX))

DECLARE curHelp CURSOR FAST_FORWARD
FOR
-- get text of all stored procedures that contain search string
-- I am using custom escape character here since i need to espape [ and ] in     search string
SELECT DISTINCT 'sp_helptext     '''+OBJECT_SCHEMA_NAME(id)+'.'+OBJECT_NAME(id)+''' ' 
FROM syscomments WHERE TEXT LIKE '%' +     REPLACE(REPLACE(@searchFor,']','\]'),'[','\[') + '%' ESCAPE '\'
ORDER BY 'sp_helptext '''+OBJECT_SCHEMA_NAME(id)+'.'+OBJECT_NAME(id)+''' '

OPEN curHelp

FETCH next FROM curHelp INTO @sqlToRun

WHILE @@FETCH_STATUS = 0
BEGIN
   --insert stored procedure text into a temporary table
  INSERT INTO @temp
   EXEC (@sqlToRun)

   -- add GO after each stored procedure
   INSERT INTO @temp
   VALUES ('GO')

   FETCH next FROM curHelp INTO @sqlToRun
END

CLOSE curHelp
DEALLOCATE curHelp

-- find and replace search string in stored procedures 
-- also replace CREATE PROCEDURE with ALTER PROCEDURE
UPDATE @temp
SET spText = REPLACE(REPLACE(spText,'CREATE PROCEDURE', 'ALTER     PROCEDURE'),@searchFor,@replaceWith)

SELECT spText FROM @temp
-- now copy and paste result into new window
-- then make sure everything looks good and run
GO

答案 3 :(得分:-2)

如果sp_HelpText返回一个表,为什么不使用游标循环结果并将结果字符串连接在一起?这很讨厌,但会做到这一点。