Loop headaches

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dbrewerton
    New Member
    • Nov 2009
    • 115

    Loop headaches

    Hello folks. I'm kinda stumped here so I could use a second pair of eyes. I'm trying to increment the x_device_id variable to the next ID in the database. MySQL is complaining about my incrementing the ID for some stupid reason. Here is what I have:

    Code:
    DELIMITER $$
    DROP PROCEDURE IF EXISTS `monthly_btus` $$
    CREATE PROCEDURE `monthly_btus`()
    
    BEGIN
    
    DECLARE x_device_id bigint;
    DECLARE startdate TIMESTAMP;
    DECLARE monthenddate TIMESTAMP;
    declare my_slice bigint;
    declare monthly_btus bigint;
    declare lastdate timestamp;
    
    select device_id from ewise_device limit 1 into x_device_id;
    
    main_loop: LOOP
    
    if (x_device_id IS NULL) then
      LEAVE main_loop;
    end if;
    
    set startdate = (SELECT last_day( NOW( ) - INTERVAL 2 MONTH )); # Gets last timestamp of 2 months ago
    set monthenddate = (SELECT DATE_FORMAT(NOW() ,'%Y-%m-01')); # Gets last timestamp for last month
    
    SELECT slice_id FROM `ewise_slice` WHERE device_id = x_device_id AND slice_timestamp BETWEEN startdate AND monthenddate ORDER BY slice_id DESC LIMIT 1 INTO my_slice;
    
    SELECT slice_timestamp FROM `ewise_slice` WHERE device_id = x_device_id AND slice_timestamp BETWEEN startdate AND monthenddate ORDER BY slice_id DESC LIMIT 1 INTO lastdate;
    
    select cumul_btus from ewise_cumulative_btus where slice_id = my_slice INTO monthly_btus;
    
    INSERT into ewise_arch_btus (device_id,enddate,totalbtus) values(x_device_id,lastdate,monthly_btus)
    set x_device_id = x_device_id + 1;
    
    END LOOP main_loop;
    END $$
    
    DELIMITER ;
    Call me crazy but I really don't see why it doesn't like it. I took out my select echo statements so the code isn't so long.
Working...