`

Oracle存储过程、触发器

    博客分类:
  • DB
 
阅读更多
1、存储过程

创建一个简单的存储过程:接收两个参数,插入到test_table表中
create or replace procedure proctest (a in VARCHAR2, b in VARCHAR2)
is
begin
  insert into test_table (test_id, test_content) values (a, b);
end proctest;


创建一个带输出的存储过程:接收参数a,输出参数b
create or replace procedure proctest2 (a in VARCHAR2, b out VARCHAR2)
is
begin
  insert into test_table(test_id) values (a);
  select test_id into b from test_table where test_id=a;
end proctest2;


创建一个存储过程,使用For循环遍历游标:
create or replace procedure proc_test is
begin
Declare 
     Cursor myCur is select * from emp;
  Begin
     for varA in myCur
      loop
         update USER set user_type=varA.emp_type where user_code=varA.emp_code;
      end loop;
  End;
  commit;
  Exception
   WHEN OTHERS
   Then
      rollback;
end proc_test;

--执行存储过程:
exec proc_test;
--删除存储过程:
DROP PROCEDURE proc_test;


当表名、字段名、数据库名作为存储过程的参数时,需要用动态sql,再用execute immediate来运行。
动态sql是一个字符串,用连接符||连接sql字符串(动态sql中的连接符||相当于java字符串的连接符+)。

java调用存储过程范例,见附件

存储过程一些资料:
http://www.cnblogs.com/sumsen/archive/2012/05/30/2525431.html
http://www.bitscn.com/pdb/oracle/200806/144607.html
http://www.cnblogs.com/hero4china/articles/base_rule_oracle_procedure.html
http://www.cnblogs.com/kkcheng/archive/2010/03/19/1689672.html
http://www.itpub.net/thread-1132571-1-1.html
http://tech.163.com/05/0707/09/1O24HIJ400091589.html
http://www.itpub.net/thread-1384981-1-1.html
http://www.cnblogs.com/superjt/archive/2013/06/09/3129403.html

java调用oracle存储过程 返回多个结果集:
http://blog.csdn.net/jzy23682891/article/details/10019721


2、触发器

oracle中创建触发器时加for each row时,是行级触发器,否则就是语句级触发器

行级(for each row)选项决定了触发器是行级还是语句级,如规定了for each row ,则触发器每影响表一行,就执行一次;否则,触发器仅仅在相应的语句被执行时触发一次,而不是针对每行。

行级触发器对DML语句影响的每个行执行一次,语句级触发器对每个DML语句执行一次。比如,如果在表中插入的数据为500行,那么这个表上的语句级触发器只执行一次,而行级触发器就要执行500次。语句触发器都只会针对指定语句激活一次。比如一条update语句,无论update了多少行,也只会调用一次update语句触发器。

对于行级触发器而言,当一个DML语句操作影响到表中的多行记录时,行级触发器会针对每一行执行一次。
在行级触发器中有一个特点,当创建before行级触发器时,可以在触发器中引用受到影响的行值,甚至可以在触发器中设置它们。
只有在行触发器中才能使用:new和:old来访问列的新值和旧值,语句级触发器不可以。

下面将在表上创建一个行级触发器,并使用序列生成主键值,这是非常常见的for each row触发器的用途。
create or replace trigger "trig_test"
    before
insert on test
    for each row
declare
  -- local variables here
begin
  select test_seq.nextval into :new.id from dual;
end trig_test ;
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics