plsql %type、%rowtype、record 详解
1 概述
1. %type、%rowtype、record 的意思及作用?
(1) 均指 引用 数据类型
(2) 声明的类型 自动引用 表字段的类型
-- 原来:varchar2(30) name 改成 varchar2(50) ,则需 重新声明数据类型
-- 现在:name%type name 无论怎么改,都不需 重新声明数据类型
2. %type、%rowtype、record 的引用范围
(1) %type : 声明 单个 字段
(2) %rowtype: 声明 所有 字段
(3) record : 声明 部分 字段 -- 字段类型及顺序 必须一致!
2 示例
-- 基础数据准备 create table scott.student_info ( sno number(3), sname varchar2(30), sex varchar2(2) ); insert into scott.student_info(sno, sname, sex) values(1, 瑶瑶, 女); insert into scott.student_info(sno, sname, sex) values(2, 优优, 男); insert into scott.student_info(sno, sname, sex) values(3, 阿梦, 女); commit;
示例:分别根据 sno 查询数据
declare
-- 1. %type:声明单个
v_sname scott.student_info.sname%type; -- 等同于 v_sname varchar(30)
-- 2. %rowtype:声明所有
v_student_info scott.student_info%rowtype;
-- 3. record:声明部分
type record_student_info is record(
v_sno scott.student_info.sno%type,
v_sname scott.student_info.sname%type);
v_student_info_record record_student_info;
begin
-- 1. %type:根据 sno = 1 查询 sname
select si.sname
into v_sname
from scott.student_info si
where si.sno = 1;
dbms_output.put_line(%type : sname = || v_sname);
-- 2. %rowtype:根据 sno = 2 查询 所有记录
select si.*
into v_student_info
from scott.student_info si
where si.sno = 2;
dbms_output.put_line(%rowtype: sno = || v_student_info.sno ||
, sname = || v_student_info.sname ||
, sex = || v_student_info.sex);
-- 3. record:根据 sno = 3 查询 部分记录
select si.sno,
si.sname
into v_student_info_record
from scott.student_info si
where si.sno = 3;
dbms_output.put_line(%record : sno = || v_student_info_record.v_sno ||
, sname = || v_student_info_record.v_sname);
exception
when others then
dbms_output.put_line(sqlerrm);
end;
查询结果:
%type : sname = 瑶瑶 %rowtype: sno = 2, sname = 优优, sex = 男 %record : sno = 3, sname = 阿梦
3 扩展
3.1 varry、table 数组类型
下一篇:
【RocketMQ】--架构模型及流程
