【发布时间】:2016-12-05 13:00:23
【问题描述】:
背景
我正在尝试创建一个可重用的 PL/SQL 过程来从一个移动数据 数据库到另一个。
为此,我使用了动态 SQL。
如果我使用带有占位符的 REPLACE,该过程将完美执行。 但是,出于安全原因,我想使用绑定变量。
问题
如何使整个 PL/SQL 代码块动态化(使用绑定 变量)?如果我使用 REPLACE 而不是绑定变量,它可以工作 很好。
如何复制
要在您的数据库中复制它,请按原样创建以下过程:
create or replace procedure move_data(i_schema_name in varchar2, i_table_name in varchar2, i_destination in varchar2) as
l_sql varchar2(32767);
l_cursor_limit pls_integer := 500;
l_values_list varchar2(32767);
begin
select listagg('l_to_be_moved(i).' || column_name, ', ') within group (order by column_id)
into l_values_list
from all_tab_cols
where owner = i_schema_name and
table_name = i_table_name and
virtual_column = 'NO';
l_sql := q'[
declare
l_cur_limit pls_integer := :l_cursor_limit;
cursor c_get_to_be_moved is
select :i_table_name.*, :i_table_name.rowid
from :i_table_name;
type tab_to_be_moved is table of c_get_to_be_moved%rowtype;
l_to_be_moved tab_to_be_moved;
begin
open c_get_to_be_moved;
loop
fetch c_get_to_be_moved
bulk collect into l_to_be_moved limit l_cur_limit;
exit when l_to_be_moved.count = 0;
for i in 1.. l_to_be_moved.count loop
begin
insert into :i_table_name@:i_destination values (:l_values_list);
exception
when others then
dbms_output.put_line(sqlerrm);
l_to_be_moved.delete(i);
end;
end loop;
forall i in 1.. l_to_be_moved.count
delete
from :i_table_name
where rowid = l_to_be_moved(i).rowid;
for i in 1..l_to_be_moved.count loop
if (sql%bulk_rowcount(i) = 0) then
raise_application_error(-20001, 'Could not find ROWID to delete. Rolling back...');
end if;
end loop;
commit;
end loop;
close c_get_to_be_moved;
exception
when others then
rollback;
dbms_output.put_line(sqlerrm);
end;]';
execute immediate l_sql using l_cursor_limit, i_table_name, i_destination, l_values_list;
exception
when others then
rollback;
dbms_output.put_line(sqlerrm);
end;
/
然后你可以执行以下程序:
begin
move_data('MySchemaName', 'MyTableName', 'MyDatabaseLinkName');
end;
/
【问题讨论】:
-
标识符(表名、模式名等)无法绑定。
-
@NicholasKrasnov 谢谢!我想我只会验证输入变量。能否请您输入与答案相同的内容,以便我关闭它?
标签: oracle plsql dynamic-sql bind-variables