【问题标题】:PL-SQL cursor that increments the salary of employees of I.T. Dept. by 20% in MySql增加 IT 员工工资的 PL-SQL 游标。部门在 MySql 中增加 20%
【发布时间】:2021-10-16 23:37:19
【问题描述】:

我必须向 IT 部门的所有员工更新 20% 的加薪。 在 MySQL 工作台中。

创建下表: Emp(E_ID, E_Name, E_Dept, E_Salary)

在 Emp 表中插入适当的数据。 属性 E_Dept 包含诸如(IT、Accounts、Sales)之类的值。 编写一个增加 IT 员工工资的 PL-SQL 游标。部门 20%。

我写了查询,

    create procedure up()
     begin

     DECLARE  v_employee_id INT;
         enter code hereDECLARE  v_salary      NUMERIC(8,2);
      DECLARE  v_last_emp    INT DEFAULT 0;

delcare emp_cur cursor for select empid,salary from employee where dept = IT for update;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET  v_last_emp=1;
START TRANSACTION;

open emp_cur;
emp_loop: LOOP

fetch emp_cur into v_employee_id, v_salary;
if v_last_emp then
leave emp_loop;
end if

update employee set salary = salary + salary * 0.20 where current of emp_cur;

end loop emp_loop;
close emp_cur;
set v_last_emp =0;
end;

【问题讨论】:

  • PL/SQL 仅适用于 Oracle,所以我不确定您的意思。

标签: mysql mysql-workbench


【解决方案1】:

不要为此使用游标,这是基本的 SQL。只需执行以下操作,我为dept 过滤器添加了单引号,假设这是一个文本字段,但如果不是,请相应调整:

UPDATE employee SET salary = 1.2 * salary WHERE dept = 'IT';

【讨论】:

  • 感谢评论,但有一个条件只能使用光标
  • 好的,但这没有任何意义。游标非常“反 SQL”,效率不高,因为它们循环遍历记录。要像你提到的那样更新所有行,一个简单的 UPDATE 是 SQL 世界的方式。
  • 明白了,但这是我的大学作业:=== 创建下表: Emp(E_ID, E_Name, E_Dept, E_Salary) 将适当的数据插入到 Emp 表中。属性 E_Dept 包含诸如 (IT, Accounts, Sales) 之类的值。编写一个 PL-SQL 游标来增加 IT 员工的薪水。部门 20%。
  • 好的,我尝试了不同的逻辑,但没有得到想要的输出。
  • 也许这对你有帮助,只需将salary + 5000 替换为salary * 1.2:javatpoint.com/pl-sql-cursor
【解决方案2】:

无需将其作为过程或循环运行

但是你的代码有问题

    create procedure up()
     begin

     DECLARE  v_employee_id INT;
         #enter code here
    DECLARE  v_salary      NUMERIC(8,2);
      DECLARE  v_last_emp    INT DEFAULT 0;

    declare emp_cur cursor for select empid,salary from employee where dept = 'IT' for update;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET  v_last_emp=1;
    START TRANSACTION;

open emp_cur;
    emp_loop: LOOP

        fetch emp_cur into v_employee_id, v_salary;
        if v_last_emp then
        leave emp_loop;
        end if;

        UPDATE employee 
        SET 
            salary = salary + (salary * 0.20)
        WHERE
            empid = v_employee_id;

    end loop emp_loop;
close emp_cur;
set v_last_emp =0;
end;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2013-05-23
    • 1970-01-01
    • 2018-03-13
    • 2019-01-25
    • 2021-10-27
    • 2020-08-09
    相关资源
    最近更新 更多