Change Links in SQL Objects when Cloning Production to Test


For example. Suppose you have four databases. Two production and Two Test. In your production databases you have one for all of your HR information while the other is your Payroll information. So you have something like the chart below. (see Figure 1)

Figure 1

Now when you clone your production HR database to test your links for the new test instance are pointing to the production instance of Payroll (Figure 2). This means that you have to open up the newly cloned test database and point the views and procedures to the test HR database see below. Sometimes this can be very time consuming. I developed this script to help me with this issue.


Use [TestDatabase]

Declare @CurDatabaseName varchar(40)
Declare @NewDatabaseName varchar(40)
Declare @sql varchar(3000)
Set @CurDatabaseName = 'NameOfDatabaseToLookFor' --Look for this in the Views/Procedures
Set @NewDatabaseName = 'NameofDatabasetoReplaceWith' --Replace it with this Value

DECLARE @sObjectName varchar(80)
DECLARE @sObjectType varchar(80)
DECLARE @sDefinition varchar(MAX)
DECLARE @sModifiedDef varchar(MAX)

--Create Temp Table
ObjectName varchar(80) NOT NULL,
ObjectType varchar(80) NOT NULL,
ObjCurDefin varchar(max) Not NULL,
ObjNewDefin varchar(max) not Null

Insert Into ##tbl
b.Name AS [ObjectName],
CASE WHEN b.type ='p' THEN 'Stored Procedure'
WHEN b.type ='v' THEN 'View'
END AS [ObjectType]
,a.definition AS [Definition]
'CREATE ','ALTER '),'''','''') AS [ModifiedDefinition]
FROM sys.sql_modules a
( select type, name,object_id
from sys.objects
where type in (
'p' -- procedures
,'v' --views
and is_ms_shipped = 0
ON a.object_id=b.object_id
SELECT Name, 'p' as Type FROM sys.procedures
WHERE OBJECT_DEFINITION(object_id) LIKE '%' + @CurDatabaseName + '%'

Union All
) fd on b.Name = fd.Name and b.type=fd.type
order by

Select * from ##tbl

select @sql = 'bcp &quot;' +
'select ' +
'ObjNewDefin + CHAR(13)+CHAR(10) + ''GO'' as action ' +
' from ##tbl ' +
'order by ObjectName&quot; queryout C:\New_Query.txt -c -T '

exec master..xp_cmdshell @sql


The net result of this process is that it will first return all views and stored procedures where it finds the @CurDatabaseName. Once they are found then the @CurDatabaseName is replaced with @NewDatabaseName. Once this is done then it creates a file called New_Query and adds all of these script changes into one file. Upon completion of this then you can open up the script in a query window and run it in the Test instance.

Hope you find this helpful and remember to always backup your database before running this. Running this in the test environment has very limited downsize risk. If it fails you just reclone production.



Author Spotlight

David Bauernschmidt


Leave a Reply


− 4 = 3
