如何在存储过程中将数据库链接作为变量传递

时间:2019-01-31 03:58:13

标签: oracle variables plsql procedure dblink

我在桌子上有一张表格。表单中的条目将定义用于查询的链接。为了使其工作,我需要创建一个查询,该查询将针对该表进行选择,从而生成要使用的链接。这不是我将要使用的SQL,但是原理是相同的。我已经尝试了各种形式的杠和引号,但是我无法让oracle编译该过程并使用表中的字符串对链接进行查询。你能帮忙吗?

--Insert the name of a db_link here, in this case
--All that the table contains is "DEV01"

create table LINK_NAME
(LINK_NAME VARCHAR2(20));

--Now create a procedure to test selecting from the link
--Just using the string in the table to get its name:

create or replace procedure TEST_LINK is
v_link_name varchar2(10);
v_blah varchar2(10);
v_link varchar2(10);

--This passes the string "DEV01" into variable v_link:
cursor c1 is select link_name into v_link from link_name;

--This works, directly referencing the link name:
--cursor c2 is select name into v_blah from v$database@DEV01;

--This doesn't work, when I reference the link using the variable I've passed.
cursor c2 is select name into v_blah from v$database@||v_link;
--How can I get oracle to accept the variable to define the name of the link?

begin
open c1;
loop
fetch c1 into v_link;
EXIT WHEN c1%NOTFOUND;
end loop;

open c2;
loop
fetch c2 into v_blah;
EXIT WHEN c2%NOTFOUND;
end loop;
--This just lets you check the database is doing the right thing:
select distinct link_name into v_link_name from pdu.link_name;
dbms_output.put_line(v_link_name||' and '||v_blah);
end ;

1 个答案:

答案 0 :(得分:2)

使用光标获取一行是...只需避免。

 create or replace procedure TEST_LINK 
 is
   v_blah      varchar2(10);
   v_link      varchar2(10);
 begin

 select link_name
 into   v_link
 from   link_name;

 execute immediate 'select count(1) from v$database@'||v_link
 into  v_blah;

 dbms_output.put_line(v_link||' and '||v_blah);
 end test_link;