---
title: "MYSQL存储过程中使用游标 "
author: "chicony"
date: "2015-07-17T16:26:28Z"
tags: []
categories: ["数据库"]
slug: "mysql"
draft: false
lastmod: "2015-07-17T16:26:28Z"
id: 2228234
url: "https://chicony.iteye.com/blog/2228234"
---

DELIMITER $$

DROP PROCEDURE IF EXISTS getUserInfo $$

CREATE PROCEDURE getUserInfo(in date\_day datetime)  
\--   
\-- 实例  
\-- 存储过程名为：getUserInfo  
\-- 参数为：date\_day日期格式:2008-03-08  
\--  
    BEGIN  
declare \_userName varchar(12); -- 用户名  
declare \_chinese int ; -- 语文  
declare \_math int ;    -- 数学  
declare done int;

-- 定义游标  
DECLARE rs\_cursor CURSOR FOR SELECT username,chinese,math from userInfo where datediff(createDate, date\_day)=0;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;

-- 获取昨天的日期  
if date\_day is null then  
   set date\_day = date\_add(now(),interval -1 day);  
end if;

open rs\_cursor;   
cursor\_loop:loop  
   FETCH rs\_cursor into \_userName, \_chinese, \_math; -- 取数据  
     
   if done=1 then  
    leave cursor\_loop;  
   end if;

   -- 更新表  
   update infoSum set total=\_chinese+\_math where UserName=\_userName;  
end loop cursor\_loop;  
close rs\_cursor;

    END$$

DELIMITER ;