Question

I have a problem with a stored procedure I wrote. The procedure is suppose to retrieve a result set from a table where I have the Latitude and Longitude then loop through the result with a cursor and update a second table. Trouble is that latitude and longitude remain at zero and no update is made. While running the raw_data query independent it gives the expected results with valid latitude and longitude, the procedure will not see them. What is weird is the fact that zip variable is correctly seen by the fetch.

Data types for variables are the same as in both tables involved.

While I know sql I am pretty green when working with stored procedures. Any hint will be greatly appreciated.

    DELIMITER $$

CREATE PROCEDURE `updateLatLong` (state varchar(2))
BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE latitude DECIMAL(9,6) DEFAULT 0;
    DECLARE longitude DECIMAL(9,6) DEFAULT 0;
    DECLARE zip CHAR(5) DEFAULT '00000';

    DECLARE raw_data CURSOR FOR 
        SELECT SQL_NO_CACHE `Latitude`, `Longitude`, `ZIPCode`
        FROM `zip5`
        WHERE `StateAbbr`=state
        ORDER BY ZIPCode ASC;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    OPEN raw_data;

    read_loop: LOOP
        FETCH FROM raw_data INTO latitude, longitude, zip;
        /*SELECT state, zip, latitude, longitude;*/
        IF done THEN
            LEAVE read_loop;
        END IF;
        UPDATE `locations` SET `Latitude`=latitude, `Longitude`=longitude WHERE `StateAbbr`=state AND `ZIPCode`=zip;

    END LOOP;
    CLOSE raw_data;
END$$

DELIMITER ;
Was it helpful?

Solution

Ok, this is a bug in mySQL. It cost me a full day of work.

Basically you are NOT ALLOWED to use same names as columns for your variables, even the capitalization is different. So, instead of

DECLARE latitude DECIMAL(9,6) DEFAULT 0;

you should have

DECLARE var_latitude DECIMAL(9,6) DEFAULT 0;

Nicely done Oracle, this is a very old bug i got this from a 2007 bug report. I wouldn't mind if they bother to spit out some warning.

Hope this will help others when they find a similar situation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top