문제

I'm trying to create a function for calculating distances between two lat/lon points; however, the CREATE FUNCTION is breaking on the END IF; portion of the function body (confirmed by removing the IF/ELSE/END block).

Any ideas? I would like to keep the M / KM difference in there to save having to add calculations in the application.

DELIMITER $$

CREATE FUNCTION HAVERSINE
    (
        from_latitude DECIMAL(30, 15),
        from_longitude DECIMAL(30, 15),
        to_latitude DECIMAL(30, 15),
        to_longitude DECIMAL(30, 15),
        unit VARCHAR(20)
    )
    RETURNS DECIMAL(30, 15)
    DETERMINISTIC
    BEGIN
        DECLARE radius DECIMAL(30, 5);
        DECLARE distance DECIMAL(30, 15);

        IF(unit = 'MILES') THEN SET radius = '3959';
        ELSE IF(unit = 'KILOMETRES' OR unit = 'KM') THEN SET radius = '6371.3929';
        ELSE SET radius = '3959';
        END IF;

        SET distance = (
            radius * 
            ACOS(
                COS(RADIANS(from_latitude)) * 
                COS(RADIANS(to_latitude)) * 
                COS(RADIANS(to_longitude) - RADIANS(from_longitude)) + 
                SIN(RADIANS(from_latitude)) * 
                SIN(RADIANS(to_latitide))
            )
        );

        RETURN distance;
    END
도움이 되었습니까?

해결책 2

I just noticed the spaces between ELSE and IF. My bad. Removed those and it works.

다른 팁

You probably forgot to add the delimiter at the end, and switch back to the standard delimiter:

Replace the last line with the following code:

END$$
DELIMITER ;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top