createorreplaceprocedureinandout(nameinvarchar2, age innumber,outp outvarchar2) is
/*in代表输入,out代表输出*/
begin
outp:='my name is '|| name||',my age is '||age;/*相当于JAVA中的returnoutp,但是请注意,存储过程中可以return多个值*/
endinandout;
测试输出代码
1
2
3
4
5
6
7
8
9
10
11
-- Created on 2018/12/30 星期日 by ADMINISTRATOR
declare
-- Local variables here
namevarchar2(64):='数据库';
age number:=06;
out_p varchar2(64);
begin
-- Test statements here
inandout(name,age,outp=>:out_p);
/*这里的outp是存储过程中的输出参数,out_p是在测试中使用的别名*/
end;
返回游标
1
2
3
4
5
6
createorreplaceproceduresysrefcursor(id innumber, columnss outsys_refcursor) as
/*columnss outsys_refcursor 为输出游标*/
begin
opencolumnss for
select* fromemp whereempno=id;
end;
测试游标
第一种测试方法
1
2
3
4
5
6
7
8
9
10
-- Created on 2018/12/30 星期日 by ADMINISTRATOR
declare
-- Local variables here
cursoree isselect* fromemp whereempno=7934;
begin
-- Test statements here
fore inee loop
dbms_output.put_line('deptno:'||e.deptno);
endloop;
end;
输出结果如下:
第二种测试方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
-- Created on 2018/12/30 星期日 by ADMINISTRATOR
declare
-- Local variables here
cursoree isselect* fromemp whereempno=7934;
cur ee % rowtype;
begin
-- Test statements here
openee;
loop
fetchee intocur;
exit whenee%notfound;
dbms_output.put_line('name:'||cur.ename);
endloop;
closeee;
end;
上面测试结果仅仅返回一条数据。下面我来演示返回多条数据的情况。 首先请看我表中的数据
有两个job中内容为CLERK的数据。
1
2
3
4
5
6
7
8
9
10
-- Created on 2018/12/30 星期日 by ADMINISTRATOR
declare
-- Local variables here
cursoree isselect* fromemp wherejob='CLERK';
begin
-- Test statements here
fore inee loop
dbms_output.put_line('deptno:'||e.deptno);
endloop;
end;
游标返回多条数据。
由于对于初学者来说,游标可能不是很容易理解,下面我用JAVA语言来描述一下。 我们在java程序中写条件查询的时候,返回出来的数据是List<泛型>。这个操作相当于游标,说白了就是个查询而已(大家不要误认为就这么一句简单的SQL为什么要用游标,因为只是方便读者学习游标罢了,具体业务具体分析,请不要抬杠哦) 当我们要使用list中的数据时,我们使用循环调用某一条数据时,是不是就要用实体类对象点get字段。可以理解为for e in ee loop dbms_output.put_line('deptno:'||e.deptno); end loop; 这里面的e.deptno。
获取table中的column
1
2
3
4
5
6
7
8
9
10
11
12
13
14
createorreplaceprocedureintop(id innumber, print2 outvarchar2) as
e_name varchar2(64);
begin
selectename intoe_name fromemp whereempno = id;
if e_name ='ALLEN'then
dbms_output.put_line(e_name);
print2:='my name is '||e_name;
elseif e_name ='SMITH'then
print2:='打印sql'||e_name;
else
print2:='打印其他';
endif;
endif;
endintop;
稍微复杂一点存储过程
由于朋友这里有个需求需要用存储过程,进而更新一下博客。 首先我们先创建一张表
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
-- Create table
createtableCLASSES
(
id NUMBER notnull,
nameVARCHAR2(14),
classesc VARCHAR2(10),
seq NUMBER(5)
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
next1M
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints