【问题标题】:Problem when creating and executing stored procedure in mysql在mysql中创建和执行存储过程时出现问题
【发布时间】:2022-01-13 01:46:18
【问题描述】:

我在 MySQL 中创建了一个存储过程。它必须获取 5 个不同列的值并根据输入参数执行计算并将计算值更新到表中。我能够创建存储过程,但是在执行它时,它会抛出一个错误,指出“MYSQL 说:#1172 - 结果包含多行。”

下面是我的存储过程

DELIMITER $$
CREATE DEFINER=`andrew`@`localhost` PROCEDURE `st_update_userpoints`(
     in point int,
     in gold int,
     in silver int,
     in bronze int,
     in userId int)
BEGIN
     DECLARE _gold int default 0;
     DECLARE _silver int default 0;
     DECLARE _bronze int default 0;
     DECLARE _points int default 0;
     DECLARE _score int default 0;
     
     select `goldMedal`,`silverMedal`,`bronzeMedal`,`totalPoints`,`score` into @_gold,@_silver,@_bronze,@_points,@_score from `userpoints` where `userId`=userId;
     
     set _gold:=(@_gold+gold);
     set _silver:=(@_silver+silver);
     set _bronze:=(@_bronze+bronze);
     set _points:=(@_points+points);
     set _score = (@_gold*5)+(@_silver+3)+(@_bronze)+(@_points);
     
     update `userpoints` set `goldMedal`=@_gold, `silverMedal`=@_silver, `bronzeMedal`=@_bronze, `totalPoints`=@_points,
     `score`=@_score where `userId`=userId;
     END$$
DELIMITER ;

【问题讨论】:

  • 我能看到的唯一可以产生此错误的语句是:select ... from userpoints` where userId=userId;`。你确定这个 SQL 查询最多只能产生 1 行吗?
  • 是的。 userId 是唯一的。

标签: mysql stored-procedures


【解决方案1】:

where `userId`=userId 使用in userId int 左右输入参数值。因此它始终为 TRUE,除了 userpoints.userId 为 NULL 的行(在这种情况下,查询返回多行),如果提供的参数值为 NULL(并且查询不返回行),它始终为 NULL==FALSE .

使用where userpoints.userId=userId - 在这种情况下,左边部分的值是列值,右边部分的值是提供的参数值。我会检查为 NULL 提供的值...

【讨论】:

    【解决方案2】:

    终于修正了存储过程

    DELIMITER $$
    
    CREATE DEFINER=`root`@`localhost` PROCEDURE `st_update_userpoints`(
         in points int,
         in gold int,
         in silver int,
         in bronze int,
         in userId int)
    BEGIN
         DECLARE _gold int default 0;
         DECLARE _silver int default 0;
         DECLARE _bronze int default 0;
         DECLARE _points int default 0;
         DECLARE _score int default 0;
         
         select `goldMedal`,`silverMedal`,`bronzeMedal`,`totalPoints`,`score` into _gold,_silver,_bronze,_points,_score from `userpoints` where `userpoints`.`userId`=userId;
         
         set _gold:=(_gold+gold);
         set _silver:=(_silver+silver);
         set _bronze:=(_bronze+bronze);
         set _points:=(_points+points);
         set _score = (_gold*5)+(_silver*3)+(_bronze*1)+(_points);
         
         update `userpoints` set `goldMedal`=_gold, `silverMedal`=_silver, `bronzeMedal`=_bronze, `totalPoints`=_points,
         `score`=_score where `userpoints`.`userId`=userId;
         END $$
    DELIMITER ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      • 2021-06-14
      • 1970-01-01
      • 2015-05-09
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      相关资源
      最近更新 更多