1.引用型变量
declare
v_name personinfo.personinfo_name%type;
v_code personinfo.personinfo_code%type;
begin
select personinfo_name, personinfo_code
into v_name, v_code
from personinfo
where personinfo_code = '0001';
dbms_output.put_line('姓名:' || v_name || ',编号:' || v_code);
end;
2.记录型变量
declare
--记录型变量
v_per personinfo%rowtype;
begin
select *
into v_per
from personinfo
where personinfo_code = '0001';
dbms_output.put_line('id:'||v_per.personinfo_id||',code:'||v_per.personinfo_code||',name:'||v_per.personinfo_name);
end;
使用记录型变量一定要考虑场景,否则会造成效率问题。因为查询的数据很多,但最后上面只用了三个,造成浪费。
使用记录型比上面引用型更为方便。
3.循环
declare
--循环
v_num number:=1;
begin
loop
exit when v_num>10;
dbms_output.put_line(v_num);
v_num:=v_num+1;
end loop;
end;
4.游标
无参游标:
declare
--声明游标
cursor c_per is select personinfo_name,personinfo_code from personinfo;
--声明变量接收游标中的数据
v_name personinfo.personinfo_name%type;
v_code personinfo.personinfo_code%type;
begin
--打开游标
open c_per;
--遍历游标
loop
--获取游标中的数据
fetch c_per into v_name,v_code;
--退出循环条件
exit when c_per%notfound;
dbms_output.put_line(v_name||'-'||v_code);
end loop;
--关闭游标
close c_per;
end;
exit when c_per%notfound和fetch位置千万不能放错,因为notfound默认值是false,也就是默认是有值的,如果他在前的话,则会多输出一条数据两次。
有参游标:
declare
--声明游标
cursor c_per(v_dept personinfo.personinfo_deptid%type) is select personinfo_name,personinfo_code from personinfo where personinfo_deptid=v_dept;
--声明变量接收游标中的数据
v_name personinfo.personinfo_name%type;
v_code personinfo.personinfo_code%type;
begin
--打开游标
open c_per(1010102);
--遍历游标
loop
--获取游标中的数据
fetch c_per into v_name,v_code;
--退出循环条件
exit when c_per%notfound;
dbms_output.put_line(v_name||'-'||v_code);
end loop;
--关闭游标
close c_per;
end;
5.存储过程
(1)有参存储过程
create or replace procedure p_hel(i_code in personinfo.personinfo_code%type) as
v_name personinfo.personinfo_name%type;
v_code personinfo.personinfo_code%type;
begin
select personinfo_code,personinfo_name into v_code,v_name from personinfo where personinfo_deptid=i_code;
dbms_output.put_line(v_name||'-'||v_code);
end p_hel;
结果:
(2)输入输出参数存储过程
create or replace procedure p_hel(i_code in personinfo.personinfo_code%type,o_id out personinfo.personinfo_id%type) as
begin
select personinfo_id into o_id from personinfo where personinfo_code=i_code;
end;
在sql中调用测试:
declare
o_id personinfo.personinfo_id%type;
begin
p_hel('0003',o_id);
dbms_output.put_line('id:'||o_id);
end;
输出: