Oracle存储过程案例详解
创建简单存储过程(Hello World)
create or replace procedure firstP(name in varchar2) is /*这里name为的参数,in为输入,varchar2为类型*/ begin /* dbms_output.put_line(); 相当输出到控制台上,这样我们一个简单的存储过程就完成啦 记住一句话的结束使用分号结束,存储过程写完一定要执行 将它保存到数据库中 (F8)快捷键,或者点击左上角执行*/ dbms_output.put_line(我的名字叫||name);/*dbms_output.put_line相当于JAVA中的System.out.println("我的名字叫"+name);*/ end firstP;
存储过程IF判断
create or replace procedure isifp(age in number) is /*存储过程if判断以then开始,以end if; 结束*/ begin if (age > 30) then dbms_output.put_line(我已经超过30岁了); elsif(age >21 and age <= 30) then dbms_output.put_line(我是青年); elsif(age >= 10 and age <= 21) then dbms_output.put_line(我还是少年); else if (age < 10) then dbms_output.put_line(我还是个儿童); else dbms_output.put_line(我正在奋斗时期); end if; end if; end;
返回游标
create or replace procedure sysrefcursor(id in number, columnss out sys_refcursor) as /*columnss out sys_refcursor 为输出游标*/ begin open columnss for select * from emp where empno=id; end;
用JAVA语言来描述一下。 我们在java程序中写条件查询的时候,返回出来的数据是List<泛型>。这个操作相当于游标,说白了就是个查询而已
获取table中的column
create or replace procedure intop(id in number, print2 out varchar2) as e_name varchar2(64); begin select ename into e_name from emp where empno = id; if e_name =ALLEN then dbms_output.put_line(e_name); print2:=my name is ||e_name; else if e_name =SMITH then print2:=打印sql||e_name; else print2:=打印其他; end if; end if; end intop;
稍微复杂一点存储过程
-- Create table create table CLASSES ( id NUMBER not null, name VARCHAR2(14), classesc VARCHAR2(10), seq NUMBER(5) ) tablespace USERS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); -- Create/Recreate primary, unique and foreign key constraints alter table CLASSES add constraint PK_CLASSES primary key (ID) using index tablespace USERS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); -- Create sequence create sequence SEQ_CLASSES minvalue 1 maxvalue 9999999999999999999999999999 start with 2 increment by 1 cache 20; create or replace procedure proclasses(Names in varchar2, classescs in varchar) as /*在我们创建存储过程的时候as其实是is*/ id number;/*设置变量名称*/ c number; seq number; begin select SEQ_CLASSES.nextval into id from dual;/*获取下一个序列,使用into赋值给id这个变量名称*/ dbms_output.put_line(classescs= || classescs);/*打印而已*/ select count(*) into c from Classes where classesc = classescs;/*条件判断,classesc=进来的变量*/ if (c > 0) then/*当数量大于0时*/ select max(seq) + 1 into seq from Classes where classesc = classescs; dbms_output.put_line(第一个seq || seq); else if (c = 0) then seq := 0;/*如果查询出来的数量为0的时候,我们赋值seq变量为0*/ dbms_output.put_line(c=0的时候seq || seq); end if; end if; insert into classes (id, name, classesc, seq) values (id, names, classescs, seq); /*insert插入这个不用多说了,大家都明白;注意的是我们insert之后一定要提交。 不然数据没有持久化到数据库,这个insert没有任何意义了*/ end proclasses;
转载为
下一篇:
javaEE项目实践——学生信息管理系统