MySQL游标操作指南
2015-04-10来源:

本篇文章是对MySQL游标的具体使用进行了详细的分析介绍,需要的朋友参考下

测试表level

代码如下:

createtabletest.level(namevarchar(20));

再insert些数据;

初始化

代码如下:

dropprocedureifexistsuseCursor//

建立存储过程create

代码如下:

CREATEPROCEDUREuseCursor()

BEGIN

局部变量的定义declare

代码如下:

declaretmpNamevarchar(20)default'';

declareallNamevarchar(255)default'';

declarecur1CURSORFORSELECTnameFROMtest.level;

MySQL游标异常后捕捉

并设置循环使用变量tmpname为null跳出循环。

代码如下:

declareCONTINUEHANDLERFORSQLSTATE'02000'SETtmpname=null;

开游标

代码如下:

OPENcur1;

游标向下走一步

代码如下:

FETCHcur1INTOtmpName;

循环体这很明显把MySQL游标查询出的name都加起并用;号隔开

代码如下:

WHILE(tmpnameisnotnull)DO

settmpName=CONCAT(tmpName,";");

setallName=CONCAT(allName,tmpName);

游标向下走一步

代码如下:

FETCHcur1INTOtmpName;

结束循环体:

代码如下:

ENDWHILE;

关闭游标

代码如下:

CLOSEcur1;

选择数据

代码如下:

selectallName;

结束存储过程

代码如下:

END;//

调用存储过程:

代码如下:

calluseCursor()//

loop循环游标:

代码如下:

DELIMITER$$

DROPPROCEDUREIFEXITScursor_example$$

CREATEPROCEDUREcursor_example()

READSSQLDATA

BEGIN

DECLAREl_employee_idINT;

DECLAREl_salaryNUMERIC(8,2);

DECLAREl_department_idINT;

DECLAREdoneINTDEFAULT0;

DECLAREcur1CURSORFORSELECTemployee_id,salary,department_idFROMemployees;

DECLARECONTINUEHANDLERFORNOTFOUNDSETdone=1;

OPENcur1;

emp_loop:LOOP

FETCHcur1INTOl_employee_id,l_salary,l_department_id;

IFdone=1THEN

LEAVEemp_loop;

ENDIF;

ENDLOOPemp_loop;

CLOSEcur1;

END$$

DELIMITER;

repeat循环游标:

代码如下:

/*创建过程*/

DELIMITER//

DROPPROCEDUREIFEXISTStest//

CREATEPROCEDUREtest()

BEGIN

DECLAREdoneINTDEFAULT0;

DECLAREaVARCHAR(200)DEFAULT'';

DECLAREcVARCHAR(200)DEFAULT'';

DECLAREmycursorCURSORFORSELECTfusernameFROMuchome_friend;

DECLARECONTINUEHANDLERFORNOTFOUNDSETdone=1;

OPENmycursor;

REPEAT

FETCHmycursorINTOa;

IFNOTdoneTHEN

SETc=CONCAT(c,a);/*字符串相加*/

ENDIF;

UNTILdoneENDREPEAT;

CLOSEmycursor;

SELECTc;

END//

DELIMITER;

代码如下:

/*创建过程*/

DELIMITER//

DROPPROCEDUREIFEXISTStest//

CREATEPROCEDUREtest()

BEGIN

DECLAREdoneINTDEFAULT0;

DECLAREaVARCHAR(200)DEFAULT'';

DECLAREcVARCHAR(200)DEFAULT'';

DECLAREmycursorCURSORFORSELECTfusernameFROMuchome_friend;

DECLARECONTINUEHANDLERFORNOTFOUNDSETdone=1;

OPENmycursor;

REPEAT

FETCHmycursorINTOa;

IFNOTdoneTHEN

SETc=CONCAT(c,a);/*字符串相加*/

ENDIF;

UNTILdoneENDREPEAT;

CLOSEmycursor;

SELECTc;

END//

DELIMITER;

更多信息请查看IT技术专栏

推荐信息
Baidu
map