gpt4 book ai didi

MySQL - 在存储过程中的游标内使用 SELECT INTO 语句

转载 作者:行者123 更新时间:2023-11-29 16:22:56 32 4
gpt4 key购买 nike

我正在 MySQL 数据库中编写存储过程,使用游标来迭代记录。我能够获取 FETCH 语句中指定的变量内的记录,但是当我在游标内使用 SELECT 时,我无法将结果存储在变量中。我知道它是可能的,但无法找出为什么它在下面的 MySQL 代码中不起作用。

CREATE DEFINER=`root`@`localhost` PROCEDURE `add_monthly_leave_entitlement`
(IN `emp` INT(10), OUT `experience` INT(10), OUT `entitlement` DECIMAL(10,4)) DETERMINISTIC
BEGIN

DECLARE emp_no INT(10);
DECLARE current_month_exp INT(10);
DECLARE previous_month_end_exp INT(10);
DECLARE emp_status INT(10);

DECLARE done INT DEFAULT FALSE;
DECLARE monthly_entitlement decimal(8,4) DEFAULT 0;

DECLARE emp_cursor CURSOR FOR
SELECT e.`emp_number` AS emp_no,
TIMESTAMPDIFF( YEAR, e.`joined_date` , NOW( ) ) AS month_start_exp,
TIMESTAMPDIFF( YEAR, e.`joined_date`, LAST_DAY(NOW()- INTERVAL 1 MONTH) ) AS last_month_end_exp, e.`emp_status` AS emp_status
FROM `hs_hr_employee` AS e
WHERE e.`termination_id` is null AND e.`emp_number`=emp;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN emp_cursor;

read_loop : LOOP
FETCH emp_cursor INTO emp_no, current_month_exp, previous_month_end_exp, emp_status;
IF done THEN
LEAVE read_loop;
END IF;

/*Monthly entitlement as per experience*/
SELECT `monthly_entitlement` INTO monthly_entitlement
FROM `ohrm_leave_entitlement_conf`
WHERE `year_completion` = IF(previous_month_end_exp >4 , 5, previous_month_end_exp)
AND `leave_type_id` = 4;

SET experience = previous_month_end_exp;
SET entitlement = monthly_entitlement;

END LOOP;

CLOSE emp_cursor;
END

无法获取monthly_entitlemententitlement内的值,该值始终为0.0000。我尝试在单独的过程中运行每月权利查询,它返回正确的值。我有表列和变量的匹配数据类型。

有人可以帮助我理解这里出了什么问题吗?

最佳答案

避免将局部变量命名为列名,请参阅 Chapter 2 Restrictions on Stored Programs :: Name Conflicts within Stored Routines 。尝试更改以下内容:

...
-- DECLARE monthly_entitlement decimal(8,4) DEFAULT 0;
DECLARE _monthly_entitlement decimal(8,4) DEFAULT 0;
...
/*Monthly entitlement as per experience*/
-- SELECT `monthly_entitlement` INTO monthly_entitlement
SELECT `monthly_entitlement` INTO _monthly_entitlement
...
-- SET entitlement = monthly_entitlement;
SET entitlement = _monthly_entitlement;
...

关于MySQL - 在存储过程中的游标内使用 SELECT INTO 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54437505/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com