2011-08-01 173 views
0
read_loop: 
LOOP 
    FETCH device_cur INTO device; 
    IF done1 THEN 
     LEAVE read_loop; 
    END IF; 
    set x = start; 
    repeat 
     SET tripcount = 0; 
     SET trip_previous = 0; 
     SELECT MAX(distinct(trip)) into tripcount from model_erv40 where date(log_time) = date(x) and device_id = device; 
     IF tripcount > 0 THEN 
      set y = 1; 
      repeat 
       SET cd = 0; 
       SELECT IFNULL(MAX(cumulative_distance), 0) into cd from model_erv40 where trip = y and date(log_time) = date(x) and device_id = device; 
       if cd > 0 then 
        if trip_previous = 0 then 
         set cdold = 0; 
         set cdcorrect = cd; 
        else 
         SELECT IFNULL(MAX(cumulative_distance), 0) into cdold from model_erv40 where trip = trip_previous and date(log_time) = date(x) and device_id = device; 
         set cdcorrect = cd - cdold; 
        end if; 

        SELECT users.id, users.verified INTO user_idv, verified FROM users INNER JOIN devices ON users.id = devices.user_id AND devices.id = device; 
        SELECT IFNULL(attribute_value, '') INTO group_code from user_attributes ua where ua.user_id = user_idv and ua.attribute_id = 1; 

        INSERT INTO trip_info(trip, user_id, device_id, IsVerified, groupcode, date, cumulative_distance) VALUES (y, user_idv, device, verified, IFNULL(group_code,''), x, ROUND(cdcorrect*0.0006214,2)); 
        SET trip_previous = y; 
       end if; 

       set y = y + 1; 
      until y > tripcount 
      end repeat; 
     END IF; 
     set x = date_add(x, interval 1 day); 
    until x > enddate 
    end repeat; 
END LOOP; 

不工作,如果我去掉語句環在MySQL存儲過程

SELECT INTO g.groupcode從group_code用戶üINNER JOIN user_attributes UA ON u.id = ua.user_id和UA。 attribute_id = 1 AND u.id = user_id INNER JOIN groupcode_master g ON ua.attribute_value = g.groupcode;

然後循環工作正常,我得到的所有設備的數據,但添加後,上述說法我只獲取數據只有一個設備,這意味着循環不繼續,但我想通過所有設備與上述聲明。請幫助我..提前感謝。

+0

'tripcount'是什麼?它的價值是什麼? 'y'的初始值是多少? –

+0

SET tripcount = 0; SET trip_previous = 0; 從model_erv40中選擇MAX(distinct(trip))到tripcount,其中date(log_time)= date(x)和device_id = device; 這是設備每天進行的行程計數。 – Ppm

+0

什麼是'log_time'和'x'?你檢查他們的值是否正確?我的想法是'tripcount'是1或0,這就解釋了爲什麼循環只執行一次。 –

回答

0

我有兩個注意事項:

... 
INNER JOIN user_attributes ua ON u.id = ua.user_id AND ua.attribute_id = 1 AND u.id = user_id 
... 
  1. 「u.id = user_ID的」 - 如果「USER_ID」是一個聲明的變量,它應該改名,因爲有一個字段名稱相同的「 user_id'

  2. ua.attribute_id = 1 - 不應該在WHERE子句中嗎?

+0

我已將聲明的變量名更改爲user_idv,並將語句更改爲「從user_attributes ua中選擇IFNULL(attribute_value,'')INTO group_code,其中ua.user_id = user_idv和ua.attribute_id = 1;」。 還有一件事user_attribute還包含group_code所需的值,其中屬性ID爲1. 但它仍然給出了相同的結果,我的意思是循環只運行一次。 – Ppm

+0

我建議你調試這個sp,你可以用dbForge Studio中的調試工具來完成 - http://www.devart.com/dbforge/mysql/studio/code-debugger.html – Devart