oracle 自定义类型(type)的用法

emp表数据如下所示

定义object类型

create or replace type typeof_userinfo_row as object(
  user_id varchar2(50),
  user_name varchar2(50)
)

创建函数并将此类型作为返回值类型

create or replace function FUN_TEST
return typeof_userinfo_row
is

  FunctionResult typeof_userinfo_row;

begin

  FunctionResult:=typeof_userinfo_row(null,null);
  
  --将单条数据值插入到自定义类型的变量中
  SELECT e.empno,e.ename  INTO FunctionResult.user_id,FunctionResult.user_name
  FROM emp e where e.empno = '7499';

  RETURN(FunctionResult);

end FUN_TEST;

调用该函数,并打印执行结果

declare res typeof_userinfo_row;

begin
  res := FUN_TEST();
  
  dbms_output.put_line(res.user_id || ' ' || res.user_name);
  
end;

执行结果

定义table类型

create or replace type typeof_userinfo_table is table of typeof_userinfo_row

创建函数并将此类型作为返回值类型

create or replace function FUN_TEST1
return typeof_userinfo_table
is

  FunctionResult typeof_userinfo_table;
begin
  --将多条记录的值同时插入到自定义类型的变量中
  SELECT typeof_userinfo_row(empno,ename) BULK COLLECT INTO FunctionResult FROM emp e;
    
  RETURN(FunctionResult);

end FUN_TEST1;

调用该函数,并打印执行结果

declare 
res typeof_userinfo_table;
i NUMBER := 1;

begin
  res := FUN_TEST1();
  
  WHILE i <= res.LAST  LOOP
  	DBMS_OUTPUT.PUT_LINE(res(i).user_id || ' ' ||res(i).user_name);
	 
		i := i + 1;
	END LOOP;
 
end;

执行结果

其他用法参考文章:【Oracle】TYPE定义的数据类型_oracle type类型_Do_GH的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/liangmengbk/article/details/131352051
今日推荐