I am writing an oracle stored procedure to synch data between our databases. We have dev, test, stage, and performance databases. I plan to use DB Links.
The problem I'm trying to solve is I want to be able to synch data into the dev database from any of the other 3 databases. I can create 3 DB Links in the dev database (pointing at test, stage, and performance) and pull data from the other 3 as needed. The problem is I don't know how I can dynamically change the db link in my stored proc. I want to avoid trying to use dynamic sql with execute immediate - that just leads to ugly string concatenation code. As an example, I have to either have 1 proc per db link or I have to have ugly if else blocks like this (keeping in mind this is just an example and I have many long queries in the procedure):
if (parm_env = 'test') then
insert into table A select * from table A@test_link
elsif (parm_env = 'stage') then
insert into table A select * from table A@stage_link
elsif (parm_env = 'performance') then
insert into table A select * from table A@performance_link
end if;
...
if (parm_env = 'test') then
insert into table B select * from table B@test_link
elsif (parm_env = 'stage') then
insert into table B select * from table B@stage_link
elsif (parm_env = 'performance') then
insert into table B select * from table B@performance_link
end if;
...
if (parm_env = 'test') then
insert into table C select * from table C@test_link
elsif (parm_env = 'stage') then
insert into table C select * from table C@stage_link
elsif (parm_env = 'performance') then
insert into table C select * from table C@performance_link
end if;
I would rather have something like this where I resolve the environment specific DB link one time and use it throughout the entire procedure:
if (parm_env = 'test') then
db_link := @test_link;
elsif (parm_env = 'stage') then
db_link := @stage_link;
elsif (parm_env = 'performance') then
db_link := @performance_link;
end if;
insert into table A select * from table A@db_link;
...
insert into table B select * from table B@db_link;
...
insert into table C select * from table C@db_link;
Any thoughts how I might be able to achieve this?
execute immediateand use it anyway. That's the obvious answer. If you struggle with escaping single quotes and don't like it for this reason, try the alternate quoting mechanism instead,q'{ ... }'.