目录
一、变量
变量名 表名.字段名%type 引用型变量
变量名 表名%rowtype 记录型变量,是一整条数据
type 记录名 is record(
变量名 表名.字段名%type,
变量名 表名.字段名%type
);
变量名 记录名;
对变量进行赋值
变量名 := 值
eg:
先有test表,字段为:
name varchar2(50),
age number(4),
sex varchar2(10)
declare
eg_name test.name%type; --定义变量
eg_age test.age%type;
begin
select name,age into eg_name,eg_age from test where id=1;
end;
declare
eg_rows test%rowtype;
begin
select * into eg_rows ; --定义记录
end;
declare
type eg_columns is record(
eg_names test.name%type,
eg_sex test.sex%type
);
eg_col eg_columns ;
begin
select name, sex into eg_col from test where id=1;
end;
二、游标
游标,类似于list的下标,对于查询后的结果集,可以通过游标访问每条数据
1.普通游标
1) 声明游标
cursor 游标名 is 查询结果集
2) 打开游标
open 游标名
3) 从游标中获取数据
fetch 游标名 into 变量
游标名%found : 找到数据
游标名%notfound : 没有找到数据
4) 关闭游标
close 游标名
eg:
--还是上面的表
--1.定义游标
declare
cursor testrows is select * from test;
testrow test%rowtype;
begin
--2.打开游标
open testrows;
loop
--获取游标数据
fetch testrows into testrow;
--当没有数据时推出循环
exit when testrows%notfound;
end loop;
--关闭游标
close testrows;
end;
2、带参数游标的使用
声明游标: 其余步骤与不带参的游标一致
cursor 游标名(参数名 参数类型) is 查询结果集 ,结果集可以通过参数筛选
eg:
--还是上面的表
--1.定义游标
declare
cursor testrows(tage number) is select * from test where age = tage;
testrow test%rowtype;
begin
--2.打开游标
open testrows;
loop
--获取游标数据
fetch testrows into testrow;
--当没有数据时退出循环
exit when testrows%notfound;
end loop;
--关闭游标
close testrows;
end;
3、系统引用游标
1)声明游标
游标名 sys_refcursor
2)打开游标
open 游标名 for 结果集
3)从游标中取数据
fetch 游标名 into 变量
游标名%found : 找到数据
游标名%notfound : 没有找到数据
4)关闭游标
close 游标名
eg:
declare
--声明游标
testrows sys_refcursor;
--声明变量存储行数据
testrow test%rowtype;
begin
--打开游标
open testrows for select * from test;
--从游标中取数据
loop
fetch testrows into testrow;
exit when testrows%notfound;
end loop;
--关闭游标
close testrows;
end;
换一种遍历方式 使用for 循环,for循环不需要打开游标,关闭游标,也不需要声明变量
declare
--声明游标
cursor testrows is select * from test;
begin
--从游标中取数据,
for testrow in testrows loop
exit when testrows%notfound;
end loop;
end;
三、循环和if判断
循环有两种
--1、for循环
for 变量名 in 游标/记录 loop
end loop;
--2、loop
loop
end loop;
其中判断推出的标准为 exit where 条件
判断语法
--1、if语句
if 条件 then
elsif 条件 then
end if;
四、 系统异常
declare
begin
exception
when 异常类型 then
when others then
end;
--常见的oracle异常类型
zero_divide : 除0异常
value_error : 类型转换异常
too_many_rows : 查询出多条记录但赋值给rowtype记录一行数据
no_data_found : 没有找到数据
sqlerrm为异常信息
五、自定义异常
--定义异常
异常名 exception;
--抛出异常
raise 异常名;