Further to my previous post, I would like to copy dependent objects (such as views or procedures) to a 'static' database. However, schema names and other object prefixes are not the same between Production and Static databases...
[I've read Aaron Bertrand's articles on setting up an Audit database, but this is a little much for our needs at this time.]
After extracting the object definitions into a variable using some dynamic sql, I am running multiple replace
statements for each change so that the views/procedures still run, pulling data from the Static database.
The reason for the replace
statements is that the views/procedures have been created using differing naming conventions. Sometimes I find <dbname>.dbo.<objectname>
, other times it's <dbname>..<objectname>
or even just dbo.<objectname>
!
Instead of using multiple replace
statements as below (I feel this may grow quite large!), is there a better method? Would a table-driven approach (using a CURSOR
) be wiser/wisest?
[Database/object names have been modified in the code below for simplicity]
declare @sql nvarchar(500), @parmdef nvarchar(500),
@dbname varchar(20), @objname varchar(255), @ObjDef varchar(max);
set @dbname = 'ProdC';
--declare cursor; get object name using cursor on dbo.ObjectsToUpdate
--[code removed for simplicity]
set @sql = N'USE '+quotename(@dbname) +'; ' ;
set @sql = @sql + N'SELECT @def=OBJECT_DEFINITION(OBJECT_ID(''dbo.'+@objname+ '''));'
set @parmdef = N'@def nvarchar(max) OUTPUT' ;
exec sp_executesql @sql, @parmdef, @def=@ObjDef OUTPUT;
--Carry out object definition replacements
set @ObjDef= replace(@ObjDef, 'CREATE VIEW [dbo].[', 'ALTER VIEW ['+@dbname+'].[');
set @ObjDef= replace(@ObjDef, 'Prod1.dbo.', @dbname+'.'); --replace Prod1 with @dbname
set @ObjDef= replace(@ObjDef, ' dbo.', ' '+@dbname+'.'); --replace all 'dbo.'
set @ObjDef= replace(@ObjDef, 'dbo.LookupTable1', @dbname+'.LookupTable1');
--[code removed for simplicity]
exec(@ObjDef);
--get next object name from cursor
--[remaining code removed for simplicity]
Many thanks in advance.