我的数据库中有800多个函数。我需要动态修改其源数据库并创建快照。
函数示例:
create function [schema1].[funTest1] (@param1 varchar(50))
returns table as
return
(
select * from [curr_database1].[schema1].[funTest1](@param1)
union
select * from [curr_database2].[schema1].[funTest1](@param1)
)
我要将脚本更改为:
create or alter function [schema1].[funTest1] (@param1 varchar(50))
returns table as return
(
select * from [new_database2].[schema1].[funTest1](@param1)
union
select * from [new_database3].[schema1].[funTest1](@param1)
)
基本上,我使用sys.syscomments获得了所有功能脚本。我正在寻找一个选项来动态查找和替换数据库以创建快照。
我如何得到它?谢谢!
这是我为共享而开发的示例代码。函数中的所有数据库均以相同的文本开头(例如“ curr”)。请分享您的想法。提前致谢!
create or alter proc test_proc as
begin
set nocount on
-- this piece of code has the new databases
if object_id('tempdb..#dbNames') is not null drop table #dbNames
create table #dbNames (dbName varchar(1000), id int)
insert into #dbNames(dbName, id) values ('new_database2', 1),('new_database3', 2)
insert into #dbNames(dbName, id) values ('new_database8', 3),('new_database9', 4)
-- this one has the sample functions
if object_id('tempdb..#dbFunctions') is not null drop table #dbFunctions
create table #dbFunctions (funText nvarchar(max))
insert into #dbFunctions (funText) values('create function [schema1].[funTest1] (@param1 varchar(50))
returns table as
return
(
select * from [curr_database1].[schema1].[funTest1](@param1)
union
select * from [curr_database2].[schema1].[funTest1](@param1)
)'),
('create function [schema2].[funTest2] (@param1 varchar(50), @param2 varchar(100))
returns table as
return
(
select * from [curr_database4].[schema2].[funTest2](@param1, @param2)
union
select * from [curr_database5].[schema2].[funTest2](@param1, @param2)
)')
-- declare variables and assign value for @frmStr variable (for testing purposes)
declare @str nvarchar(max)
declare @dbName varchar(100)
declare @frmStr varchar(100) = '[curr_database1]'
-- get the total count of the databases and the functions to iterate and replace the string
declare @dbCnt int = (select count(id) from #dbNames)
declare @fnCnt int = (select count(*) from #dbFunctions)
while @dbCnt > 0
begin
set @dbname = (select dbname from #dbnames where id = @dbcnt)
while @fnCnt > 0
begin
-- this is where I would need to replace the code
select @str = replace(funText, @frmStr, @dbName) from #dbFunctions
select @str
set @fnCnt = @fnCnt - 1
end
set @dbCnt = @dbCnt - 1
end
end
答案 0 :(得分:0)
您的实际目标尚不清楚,但是要回答您所提出的问题,您可以在查询中使用REPLACE函数对最初用于获取代码的系统注释:
REPLACE(
REPLACE([FunctionTextColumn],'curr_database1','new_database2')
,'curr_database2','new_database3'
)