使用oracle的存储过程的例子

十几年没有用oracle的存储过程了,有些东西已经忘了,没有想到今天又要用。在这里写个例子。
它演示了存储过程的格式,游标的使用,循环、判断的使用,还有直接执行一个拼接的SQL的用法。
以下是代码:

create or replace procedure wanglc_test is
  v_table_name varchar2(50);
  v_sql        varchar2(4000);

  cursor cur_get_users is
    select username, created from all_users;
  v_username varchar2(50);
  v_created  date;
begin
  dbms_output.put_line(to_char(sysdate, 'yyyy-mm-dd hh24:mi:ss') ||
                       ' call procedure wanglc_test begin...');

  open cur_get_users;
  loop
    fetch cur_get_users
      into v_username, v_created;
    exit when cur_get_users%notfound;
  
    dbms_output.put_line(to_char(sysdate, 'yyyy-mm-dd hh24:mi:ss') || ' ' ||
                         v_username || ' -- ' || v_created);
  
    if (v_username = 'SYS' or v_username = 'SYSTEM') then
      dbms_output.put_line(to_char(sysdate, 'yyyy-mm-dd hh24:mi:ss') || ' ' ||
                           v_username || ' is DBA!!!');
      /*
      insert into sys_user(name,created) values('SYS',sysdate)
      */
      v_sql := 'insert into sys_user(name,created) values(''' || v_username ||''',sysdate)';
      dbms_output.put_line(to_char(sysdate, 'yyyy-mm-dd hh24:mi:ss') || ' ' ||
                           v_sql);

      execute immediate v_sql;
      execute immediate 'commit';
    end if;
  
  end loop;
  close cur_get_users;

  dbms_output.put_line(to_char(sysdate, 'yyyy-mm-dd hh24:mi:ss') ||
                       ' call procedure wanglc_test end.');
end wanglc_test;


如果存储过程编译出错,可以在这里找错误点:
select * from all_errors where name = upper('wanglc_test');

在命令行执行存储过程
SQL> set serveroutput on size 10000000;
SQL> exec wanglc_test;
2019-06-04 23:56:33 call procedure wanglc_test begin...
2019-06-04 23:56:33 ACCT_OSCXK -- 21-5月 -19
2019-06-04 23:56:33 CUST_OCS0520 -- 20-5月 -19
2019-06-04 23:56:33 ACCT0520 -- 20-5月 -19
2019-06-04 23:56:33 WMSYS -- 24-8月 -13
2019-06-04 23:56:33 APPQOSSYS -- 24-8月 -13
2019-06-04 23:56:33 DBSNMP -- 24-8月 -13
2019-06-04 23:56:33 ORACLE_OCM -- 24-8月 -13
2019-06-04 23:56:33 DIP -- 24-8月 -13
2019-06-04 23:56:33 OUTLN -- 24-8月 -13
2019-06-04 23:56:33 SYSTEM -- 24-8月 -13
2019-06-04 23:56:33 SYSTEM is DBA!!!
2019-06-04 23:56:33 insert into sys_user(name,created) values('SYSTEM',sysdate)
2019-06-04 23:56:33 SYS -- 24-8月 -13
2019-06-04 23:56:33 SYS is DBA!!!
2019-06-04 23:56:33 insert into sys_user(name,created) values('SYS',sysdate)
2019-06-04 23:56:33 call procedure wanglc_test end.
PL/SQL procedure successfully completed

另外,可以在plsql developer中右键点击存储过程名称进行测试。此处略。

原文地址:https://www.cnblogs.com/babyha/p/11181733.html