- 第一种:execute immediate sqlstr
- 第二种:dbms_sql工具体
一、execute immediate sqlstr
create or replace procedure my_procedure()
return number
as
sqlstr varchar2(500);
table_name varchar2(100);
name varchar2(200);
num number;
begin
table_name := 'user_' || '01';
name = 'leo';
sqlstr := 'select count(*) from ' || table_name || ' where username= :name';
-- into 查询结果, using 后面放入注入参数
execute immediate sqlstr into num using name;
-- 返回结果
return num;
end;
二、dbms_sql工具体
create or replace procedure my_procedure
as
c number;
n number;
table_name varchar2(100);
begin
-- 打开游标
c := dbms_sql.open_cursor;
-- 解析sql
table_name = 'user_' || '01';
dbms_sql.parse(c, 'insert into ' || table_name
|| ' values(:userid, :username, :password)');
-- 绑定变量
dbms_sql.bind_variable(c, 'userid', '1');
dbms_sql.bind_variable(c, 'username', 'leo');
dbms_sql.bind_variable(c, 'password', '123');
-- 执行sql,并返回结果
n := dbms_sql.execute(c);
commit;
-- 关闭游标
dbms_sql.close_cursor(c);
exception
when others then
-- 处理异常
dbms_output.put_line('异常:' || sqlerrm);
rollback;
end;
dbms_output.put_line用来在command窗口打印日志,如果没打印日志:
1、set serveroutput on;
2、execute?my_procedure;
|