【问题标题】:Error Code: 1172. Results consisted in more than one row error错误代码:1172。结果包含多于一行错误
【发布时间】:2021-03-21 20:06:31
【问题描述】:

所以我有 2 个名为 Employee(employeeID, Salary) 和 Tax(employeeID, tax, revisionSalary) 的表,我的目标是通过提取 Salary 列中的值来计算所有员工的税款和修订后的薪水Employee Table,执行计算并将结果存储在 Tax 表中,所有这些都使用存储过程

这是我试图完成的,但到目前为止没有成功,我收到“结果包含多行”错误:

delimiter //
create procedure calcTax()
begin
  declare tax, salary, revisedSalary double default 0.0;
  declare i int;
  select Salary from Employee into salary;
  while i <= salary do
  if salary >= 0.0 and salary<= 10000.0
  then
    set tax = salary * 10/100;
     set revisedSalary = salary - tax;
  end if;
    insert into Tax (tax, revisedSalary) values(tax, revisedSalary);
    set i = i + 1;
end while;
end //
delimiter ;

【问题讨论】:

  • 您不能将结果集存储在标量变量中。即从Employee中选择Salary到salary;不可能
  • 您认为必须使用存储过程的任何原因?
  • @P.Salmon 我正在学习 mySQL,所以我得到了这样一个任务,我必须使用存储过程来执行这样的操作。
  • 如果任务只说使用 sp,那么您可以将我的答案放到 sp 中并且它会起作用 - 但如果没有看到措辞,我不能说我在 sp 中的代码是否能满足要求,即使它确实满足了发布的问题

标签: mysql mysql-workbench


【解决方案1】:

除了您不能将结果集存储在变量中这一事实之外,您的问题没有多大意义,因为您正在尝试计算每位员工的税金和薪水,并且您在不参考员工的情况下向税金插入行。也不需要while循环,同样可以通过简单的插入选择来实现

DROP TABLE IF EXISTS T,tax;
CREATE TABLE T
(employeeid int, salary int);
create table tax
(employeeid int, tax int , revisedsalary int);

insert into t values
(1,0),(2,5000),(3,7000),(4,15000);

insert into tax 
select employeeid,
         salary * .10,
         salary - (salary * .10)
from t
where salary > 0 and salary <= 10000;

select * from tax;

+------------+------+---------------+
| employeeid | tax  | revisedsalary |
+------------+------+---------------+
|          2 |  500 |          5000 |
|          3 |  700 |          7000 |
+------------+------+---------------+
2 rows in set (0.001 sec)

如果您必须使用 sp

delimiter $$
create procedure p()
begin
 insert into tax 
    select employeeid,
             salary * .10,
             salary - (salary * .10)
    from t
    where salary > 0 and salary <= 10000;
    
    select * from tax;
end $$
delimiter ;

call p();

【讨论】:

    猜你喜欢
    • 2018-03-07
    • 2012-03-19
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多