mysql存儲過程遊標使用

BEGIN   
	DECLARE idCount int DEFAULT 0;-- 定義查詢的id count
	DECLARE nameCount int DEFAULT 0;-- 統計相同名字合計
	DECLARE openerId int DEFAULT 0; 
	DECLARE openerName VARCHAR(255);
	-- 遍歷數據結束標誌
	DECLARE done INT  DEFAULT FALSE;
	-- 定義遊標
  DECLARE cur CURSOR FOR select count(*) count,opener FROM qf_invoice where (`status` >10 or `status` =1)  GROUP BY opener;
	-- 將結束標誌綁定到遊標
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
	-- 打開遊標
  OPEN cur;
	-- 開始循環
  read_loop: LOOP
    -- 提取遊標裏的數據,這裏只有一個,多個的話也同樣;
    FETCH cur INTO nameCount,openerName;
		SELECT nameCount,openerName;  
    -- 聲明結束的時候
    IF done THEN
			SELECT 'done';
      LEAVE read_loop;
    END IF;
    -- 業務邏輯
		SELECT id,COUNT(id) into openerId,idCount from qf_merchant_invoice where `status` = 1 and opener = openerName;
    if(idCount !=0) THEN  -- 查詢結果爲null時遊標會主動退出
			update qf_merchant_invoice SET invoice_number = invoice_number + nameCount where id = openerId;
		ELSE
			INSERT into qf_merchant_invoice(opener,invoice_number,create_time,STATUS) VALUES(openerName,nameCount,NOW(),1);
		end if;
  END LOOP;
  -- 關閉遊標
  CLOSE cur;
END

 有一點:有時候使用遊標要使用別名,否則會形成遊標結果和sql查詢不一致;java

加上別名: sql

不加別名:數據庫

數據庫直接查詢結果oop

相關文章
相關標籤/搜索