2

I'm trying to write a mySQL procedure with a cursor to calculate a fare. I pass in the stationid's then I figure out what zone they are in. The fare is a set value of $1 and an additional $0.20 for each zone traveled in. The code I have so far runs but there is a problem with the cursor not fetching the values into the variables.

Any help would be greatly appreciated. Thanks

Tables:

    DROP DATABASE IF EXISTS luasSystem;
    CREATE DATABASE luasSystem;
    USE luasSystem;

    CREATE TABLE IF NOT EXISTS line
    (
    line_id INT NOT NULL AUTO_INCREMENT,
    Line_colour CHAR(10) NOT NULL,
    PRIMARY KEY (line_id)
    )   ENGINE=InnoDB;

    CREATE TABLE IF NOT EXISTS zone
    (
    zone_id INT NOT NULL AUTO_INCREMENT,
    zone_name VARCHAR(20) NOT NULL,
        line INT NOT NULL,
    PRIMARY KEY (zone_id),
    FOREIGN KEY (line) REFERENCES line(line_id) ON UPDATE CASCADE ON DELETE RESTRICT
    )   ENGINE=InnoDB;

    CREATE TABLE IF NOT EXISTS station
    (
    station_id INT NOT NULL AUTO_INCREMENT,
    station_name CHAR(20) NOT NULL,
    service CHAR(20),
        line INT NOT NULL,
        zone INT NOT NULL,
    PRIMARY KEY (station_id),
    FOREIGN KEY (line) REFERENCES line(line_id) ON UPDATE CASCADE ON DELETE RESTRICT,
    FOREIGN KEY (zone) REFERENCES zone(zone_id) ON UPDATE CASCADE ON DELETE RESTRICT
    )   ENGINE=InnoDB;

Stored Procedure:

    DROP PROCEDURE IF EXISTS calculateFare;
    DELIMITER //
    CREATE PROCEDURE calculateFare
    (
    IN stationid1 INT, IN stationid2 INT
    )
    BEGIN

    DECLARE zoneNum1 INT;
    DECLARE zoneNum2 INT;
    DECLARE num INT;
    DECLARE fare DOUBLE;

    DECLARE tableEnd BOOLEAN;

    DECLARE zoneCur CURSOR FOR
    SELECT zone, zone FROM station
    WHERE station_name = stationid1 AND station_name = stationid2;

    DECLARE CONTINUE HANDLER FOR NOT FOUND
    SET tableEnd = TRUE;

    OPEN zoneCur;
    the_loop: LOOP

    FETCH zoneCur
    INTO zoneNum1, zoneNum2;

    IF tableEnd THEN
    CLOSE zoneCur;
    LEAVE the_loop;
    END IF;

    SET fare = 1;
    SET num = 0;

    IF zoneNum1 < zoneNum2 THEN
    SET num = zoneNum2 - zoneNum1;
    ELSEIF zoneNum1 > zoneNum2 THEN
    SET num = zoneNum1 - zoneNum2;
    END IF;

    SET fare = (num * 0.20) + 1;
    SELECT fare;
    END LOOP the_loop;
    END //
    DELIMITER ;

    CAll calculateFare(3,5);
4

1 回答 1

0

使用十进制值而不是整数会不会更容易?建议你看看:http ://dev.mysql.com/doc/refman/5.0/en/fixed-point-types.html

于 2013-04-05T21:28:02.910 回答