MySQL 带光标的函数

MySQL FUNCTION with cursor

我必须创建一个给定三个整数类型参数的函数,其中第一个代表一小时,第二个代表一分钟,第三个代表一秒,return [=15] 中的记录数=] 其中,DATETIME 类型的列,小时等于第一个参数,或者分钟等于第二个参数,或者秒等于第三个参数。我需要检查参数是否具有与它们进行比较的列的有效值,否则它 return 的值为 -1。 我已经这样做了,但它无法正常工作。

DELIMITER //
CREATE FUNCTION orders_placed(par_hour INT , par_minute INT , par_second INT )
RETURNS INT
BEGIN
DECLARE var_date DATETIME;
DECLARE var_counter INT;
DECLARE c1 CURSOR FOR SELECT date FROM orders;
            IF (par_hour NOT BETWEEN 0 AND 23 OR par_minute NOT BETWEEN 0 AND 59 OR par_second NOT BETWEEN 0 AND 59) THEN 
                    SET var_counter = -1;
            END IF; 
    OPEN c1;

        bucle: LOOP 

            FETCH c1 into var_date;

                IF (par_hour = hour(var_date) OR par_minute = minute(var_date) OR par_second = second(var_date)) THEN

                    SET var_counter= var_counter + 1;

                END IF;

        END LOOP bucle;

    CLOSE c1;
RETURNS var_counter;
END //
DELIMITER ;

您的查询存在一些问题。

DELIMITER $$
CREATE DEFINER=`root`@`localhost` FUNCTION `orders_placed`(par_hour INT , par_minute INT , par_second INT ) RETURNS int
    DETERMINISTIC
BEGIN
DECLARE var_date DATETIME;
DECLARE var_counter INT DEFAULT 0;
DECLARE finished INTEGER DEFAULT 0;
DECLARE c1 CURSOR FOR SELECT `date` FROM orders;
-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER 
    FOR NOT FOUND SET finished = 1;

    IF (par_hour NOT BETWEEN 0 AND 23 OR par_minute NOT BETWEEN 0 AND 59 OR par_second NOT BETWEEN 0 AND 59) THEN 
            SET var_counter = -1;
    ELSE 
        OPEN c1;
            bucle: LOOP 
                FETCH c1 into var_date;
                IF finished = 1 THEN 
                    LEAVE bucle;
                END IF;
                    IF (par_hour = hour(var_date) OR par_minute = minute(var_date) OR par_second = second(var_date)) THEN
                        SET var_counter= var_counter + 1;
                    END IF;
            END LOOP bucle;
        CLOSE c1;
    END IF;
RETURN var_counter;
END$$
DELIMITER ;

你确定我不想检查所有数字时分秒是否都等于你的日期,因为你只检查其中一个是否相等。