动态SQL
1. 使用execute immediate语句
1.1 语法:
execute immediate dynamic_sql
[into { variable[,variable]... | record } ]
[using [in | out | in out ] bind_argument[,[in | out | in out ] bind_argument]
[{ returning | return } into bind_argument [, bind_argument]...];
dynamic_sql : 代表一个SQL语句或者PL/SQL块的字符表达式。
variable : 是存储选择的列的一个变量值,record是存储在所选行的一用户定义的或%rowtype纪录。
bind_argument : 是传入和传出值。
using : 缺省模式为in。
returning | return : 仅在DML语句中使用。
1.2 实例:
1.2.1 执行DDL
BEGIN
execute immediate ' create table j_dynamic_sql_test '
|| ' ( id integer, name varchar2(8) )' ;
END;
/
1.2.2 绑定变量
DECLARE
sql_str varchar2(200);
type id_table is table of integer; -- ? 1. 此处定义的是什么数据类型,oracle提供了几种集合类型 ? --
type name_table is table of varchar2(8); -- ? 2. 定义表的时候,表的名字最高可以有几个字符 ? --
t_id id_table := id_table(1,2,3,4,5);
t_name name_table := name_table('test1','test2','test3','test4','test5');
v_returned_id integer;
v_returned_name varchar2(8);
BEGIN
sql_str := ' insert into j_dynamic_sql_test values ( :1 , :2 ) ';
for i in t_id.first.. t_id.last loop
execute immediate sql_str using t_id(i), t_name(i);
end loop;
sql_str := ' select id, name from j_dynamic_sql_test where id = :1';
for i in t_id.first.. t_id.last loop
execute immediate sql_str into v_returned_id, v_returned_name using t_id(i);
dbms_output.put_line('SQL inserted with id: '||v_returned_id||' and table name: '||v_returned_name);
end loop;
END;
/
1.2.3 use return
DECLARE
sql_str varchar2(512);
v_returned_id integer;
v_returned_name varchar2(32);
BEGIN
sql_str := ' insert into j_dynamic_sql_test values (:1, ''test'' ) returning id,name into :2,:3' ;
for i in 1..100 loop
execute immediate sql_str using i returning into v_returned_id,v_returned_name;
dbms_output.put_line('SQL inserted with id: '||v_returned_id ||' name: ' || v_returned_name);
end loop;
END;
2. 使用open-for , fetch 和 close语句
DECLARE
type ref_cursor_type is ref cursor;
my_cursor ref_cursor_type;
tab_rec j_dynamic_sql_test%rowtype;
sql_str varchar2(200);
BEGIN
sql_str := ' select id, name from j_dynamic_sql_test ';
sql_str := sql_str || ' order by id desc';
open my_cursor for sql_str;
loop
fetch my_cursor into tab_rec;
exit when my_cursor%notfound;
dbms_output.put_line('id: '||tab_rec.id||' and name: '||tab_rec.name);
end loop;
close my_cursor;
END;
/
ANSWERS WITH --? * ?--
1. 此处为嵌套表.oracle 提供了两个集合类型: TABLE类型和变长数组.TABLE类型又分为nested tables & index-by tables.
2. 表的名字可以有32位.