如何动态地将存储过程从一个数据库复制到同一服务器上的另一个数据库

时间:2016-09-07 13:06:04

标签: sql-server-2008 sql-server-2005

我正在尝试编写一个脚本来将存储过程复制到服务器上的另一个数据库中:

SELECT @def = [definition] 
FROM [@from_db].sys.sql_modules 
WHERE object_id = OBJECT_ID('MyProcedure') 

EXEC(@def); 

但是这不起作用,如何将存储过程从一个数据库复制到另一个数据库?

1 个答案:

答案 0 :(得分:1)

试试这个

DECLARE @SQL NVARCHAR(max) = ''
    ,@TargetDBName NVARCHAR(255) = 'TargetDBName'

DECLARE c CURSOR
FOR
SELECT DEFINITION
FROM SourceDBName.[sys].[procedures] p
INNER JOIN SourceDBName.sys.sql_modules m ON p.object_id = m.object_id

OPEN c

FETCH NEXT
FROM c
INTO @sql

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sql = REPLACE(@sql, '''', '''''')
    SET @sql = 'USE [' + @TargetDBName + ']; EXEC(''' + @sql + ''')'

    EXEC SP_EXECUTESQL @sql

    FETCH NEXT
    FROM c
    INTO @sql
END

CLOSE c

DEALLOCATE c