#Hey! Help with an sql script

1 messages · Page 1 of 1 (latest)

unborn leaf
#

so i created an sql script beacause a sensor i have was not total incrementing. it was reseting each day and i want to correct that by summing up all the history values

#

´´´CREATE DEFINER=homeassistant@% PROCEDURE fix_deye(IN metadata INT)
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE curr_id INT;
DECLARE prev_value double;
DECLARE curr_value double;
DECLARE sum_value double;
DECLARE cur1 CURSOR FOR SELECT id, state, sum FROM statistics where metadata_id = metadata;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN cur1;
FETCH cur1 INTO curr_id, curr_value, sum_value;

update statistics set sum = curr_value;

set prev_value = curr_value;

FETCH cur1 INTO curr_id, curr_value, sum_value;

read_loop: LOOP

IF done THEN
  LEAVE read_loop;
END IF;

IF curr_value - prev_value > 0 THEN
    set sum_value = sum_value + ( curr_value - prev_value );
ELSE
    set sum_value = sum_value + curr_value;
END IF;

update statistics set sum = sum_value;

set prev_value = curr_value;

FETCH cur1 INTO curr_id, curr_value, sum_value;

END LOOP;

CLOSE cur1;
END´´´

#

can any1 take a look and give any tip?

trail thunder
#

The only tip I've got is that screwing with long-term stats like that seems like a recipe for disaster. The first line in your cursor loop blasts the entire table w/ that single scalar value.

Hard to give an alternative without knowing the scenario and integrations, but if it's energy related, you could look into utility meter without a specified period.

unborn leaf
#

but when we have a opened cursor , doesnt the update instruction only updates that register it is selected?

#

it is energy related. the energy panel is all pmessed up because solar energy starts with a huge negative production. i want to fix that