简体   繁体   中英

Copying a stored procedure from one database to another

I have a central management database which collates some information and runs some dynamic SQL for various other tasks when a new database is restored into the environment. One of those tasks is going to be a bit complex to achieve through dynamic SQL so I had the idea of creating a master copy stored procedure in the central DB and copying that over to the new databases after they are restored.

I've seen a few examples of people trying to do that on here but I can't get anything to play ball.

Here's what i am trying to achieve conceptually, note that I'm trying to cater for potentially multiple stored procedures to be created in this way just for future proofing.

declare @sql nvarchar(max), @DatabaseName nvarchar(200)
set @DatabaseName = 'TargetDatabase'

set @sql =  
 (
   SELECT definition + char(13) + 'GO' 
   FROM sys.sql_modules s 
   INNER JOIN sys.procedures p 
   ON [s].[object_id] = [p].[object_id] WHERE p.name LIKE '%mastercopy%'
)

exec @sql

Thanks

Instead of creating dynamic script you could use one script with all the procedures that you want to create (you can script all the procs you want using 2 click in SSMS ), you then run this script manually in the context of the database where you want to create these procedures or by passing the file with this script to sqlcmd with -i and passing the correct database name with -d .

Here Use the sqlcmd Utility you can see the examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM