oracle中游标的使用

1、使用for来操作游标

--FOR的使用
CREATE OR REPLACE FUNCTION A_Test1(I_VAL VARCHAR2) RETURN VARCHAR2 is
     V_RESULT       VARCHAR2(50);
     CUR_BP_MARKING sys_refcursor;
     OBJ_BP_MARKING BP_MARKING%ROWTYPE;
 BEGIN
     OPEN CUR_BP_MARKING FOR SELECT * FROM BP_MARKING WHERE SFC_NO='123456789';
     LOOP FETCH CUR_BP_MARKING INTO OBJ_BP_MARKING;
          EXIT WHEN CUR_BP_MARKING%NOTFOUND;
          V_RESULT:=V_RESULT ||','|| OBJ_BP_MARKING.MARK_OPERATION_ID;
     END LOOP;
     RETURN V_RESULT;
 EXCEPTION
     WHEN OTHERS THEN
          RETURN '错误';
 END A_Test1;

for就是在开始之后才使用的。

 

2、使用is来操作游标

--IS的使用
CREATE OR REPLACE FUNCTION A_Test1(I_VAL VARCHAR2) RETURN VARCHAR2 is
     V_RESULT       VARCHAR2(50);
     CURSOR CUR_BP_MARKING IS SELECT * FROM BP_MARKING WHERE SFC_NO='123456789';
     OBJ_BP_MARKING BP_MARKING%ROWTYPE;
 BEGIN
     OPEN CUR_BP_MARKING;
     LOOP FETCH CUR_BP_MARKING INTO OBJ_BP_MARKING;
          EXIT WHEN CUR_BP_MARKING%NOTFOUND;
          V_RESULT:=V_RESULT ||','|| OBJ_BP_MARKING.MARK_OPERATION_ID;
     END LOOP;
     RETURN V_RESULT;
 EXCEPTION
     WHEN OTHERS THEN
          RETURN '错误';
 END A_Test1;

is是在定义的时候使用的。

 

 

 

使用案例:

CREATE OR REPLACE FUNCTION A_Test1(I_VAL VARCHAR2) RETURN VARCHAR2 is
     V_RESULT       VARCHAR2(50);
     CURSOR CUR_BP_MARKING IS SELECT * FROM BP_MARKING WHERE SFC_NO='H8920052505564TB030';
     OBJ_BP_MARKING BP_MARKING%ROWTYPE;
 BEGIN
     FOR OBJ_BP_MARKING IN CUR_BP_MARKING LOOP
         V_RESULT:=V_RESULT ||','|| OBJ_BP_MARKING.MARK_OPERATION_ID;
     END LOOP;
     RETURN V_RESULT;
 EXCEPTION
     WHEN OTHERS THEN
          RETURN '错误';
 END A_Test1;

 当使用游标for循环时,orcale会隐含的打开游标,提取数据并关闭游标(自动,不用写关闭语句)。

所以没有写open....close....

参考:https://www.cnblogs.com/zhiyanwenlei/p/9658262.html

 

 

=========================2021-04-09添加================================

循环遍历某个表的某些字段,不需要定义游标(隐式游标)和变量值,比较方便。

CREATE OR REPLACE FUNCTION A_Test1(I_SFC_NO VARCHAR2) RETURN VARCHAR2 is
     V_RESULT       VARCHAR2(50);
 BEGIN
     FOR CUR_BP_MARKING IN (SELECT DISTINCT MARK_NO FROM BP_MARKING WHERE SFC_NO=I_SFC_NO AND TYPE='Y' AND MARK_OPERATION_ID='1542') LOOP
         V_RESULT:=V_RESULT ||','|| CUR_BP_MARKING.MARK_NO;
     END LOOP;
     RETURN V_RESULT;
 EXCEPTION
     WHEN OTHERS THEN
          RETURN '错误';
 END A_Test1;

参考:https://blog.csdn.net/xuheng8600/article/details/85253689

posted @ 2021-01-05 20:18  masha2017  阅读(324)  评论(0编辑  收藏  举报