SQLServer复制存储过程

时间:2015-02-25 08:49:30

标签: sql-server stored-procedures

我希望有一种方法可以将存储过程的副本复制到存储过程中,其名称类似于sp_oldprocedureName_yyyymmddhhmiss,编程方式如下:
(以下代码是我的“内涵”代码)

declare @DateExtension char(14)  
select @DateExtension = substring(CONVERT(varchar(30), getdate(), 120), 1,4) + substring(CONVERT(varchar(30), getdate(), 120), 6, 2)+ substring(CONVERT(varchar(30), getdate(), 120), 9, 2)+ substring(CONVERT(varchar(30), getdate(), 120), 12, 2)+ substring(CONVERT(varchar(30), getdate(), 120), 15, 2)+ substring(CONVERT(varchar(30), getdate(), 120), 18, 2)  

declare @OldName, @NewName varchar(255)  
set @OldName = 'sp_OldProcedureName'  
set @NewName = @OldName + '_' + @DateExtension  
sp_copy(@OldName, @NewName)  --This sp_copy does not exist, but I'm looking for an equivalent.

那么,是否有类似上述“sp_copy”的程序?

2 个答案:

答案 0 :(得分:0)

好的 - 尝试以下方法。该过程应该按照您的指定工作。它将从sql_modules获取procs定义并使用新名称执行它。可能需要进行一些调试。

CREATE PROCEDURE spCopy @OLDNAME NVARCHAR(255), @NEWNAME NVARCHAR(255)
AS
BEGIN
DECLARE @SQL NVARCHAR(MAX)

    SELECT @SQL = REPLACE(definition,@OLDNAME,@NEWNAME) 
    FROM sys.sql_modules 
    WHERE object_ID(@OLDNAME) = object_id

    EXEC @SQL
END 

答案 1 :(得分:0)

您可以创建以下存储过程:

CREATE PROCEDURE sp_copy
    (@OldName VARCHAR(255),
    @NewName VARCHAR(255))
    AS BEGIN

BEGIN TRY
DECLARE @definition NVARCHAR(MAX), @sql NVARCHAR(MAX);
SELECT @definition = m.definition
   FROM sys.procedures p
   JOIN sys.sql_modules m ON p.OBJECT_ID = m.OBJECT_ID
   WHERE name LIKE @OldName;
IF @definition IS NULL
BEGIN
    PRINT 'There is no stored procedure with name: ''' + @OldName + '''';
END;
ELSE
BEGIN
    SET @definition = REPLACE(@definition, @OldName,@NewName);
    SET @definition = REPLACE(@definition, '''','''''');
    SET @sql = 'EXEC(''' + @definition + ''')';
    EXEC(@sql);
    PRINT 'Stored procedure duplicated successfully.';
END;
END TRY
BEGIN CATCH
    PRINT 'There was an issue copying the stored procedure.';
END CATCH;

END;
GO

然后执行如下代码:

DECLARE @OldName VARCHAR(255)  , @NewName VARCHAR(255);  
DECLARE @DateExtension CHAR(14);  
SELECT @DateExtension = SUBSTRING(CONVERT(VARCHAR(30), GETDATE(), 120), 1,4) + SUBSTRING(CONVERT(VARCHAR(30), GETDATE(), 120), 6, 2)+ SUBSTRING(CONVERT(VARCHAR(30), GETDATE(), 120), 9, 2)+ SUBSTRING(CONVERT(VARCHAR(30), GETDATE(), 120), 12, 2)+ SUBSTRING(CONVERT(VARCHAR(30), GETDATE(), 120), 15, 2)+ SUBSTRING(CONVERT(VARCHAR(30), GETDATE(), 120), 18, 2);  
SET @OldName = 'sp_OldProcedureName';  
SET @NewName = @OldName + '_' + @DateExtension;  
EXEC dbo.sp_copy @OldName, @NewName;