【问题标题】:MySQL procedure call from trigger always returns null for out parameters来自触发器的 MySQL 过程调用始终为 out 参数返回 null
【发布时间】:2020-07-25 15:29:36
【问题描述】:

我的存储过程的OUT参数,总是返回一个空值。

这里是示例表、触发器和过程代码。

表:test
列:

  • id - Int
  • status - enum(‘pass’, ‘fail’)(允许为空)

表格中的值:

id  |  status
1   |  null

触发器:

create trigger BEFORE_UPDATE_TEST before update on `test` for each row begin

    call Test_BEFORE_UPDATE_TEST(old.id, @updatedStatus);

       ## I always get @updatedStatus null/nil

    if (@updatedStatus is not null and @updatedStatus <> new.status) then
        set new.status = @updatedStatus;
    end if;

end;

程序:

create procedure Test_BEFORE_UPDATE_TEST (
  IN id int(5),
  OUT status enum(‘pass’, ‘fail’)
)
begin
   @status = ‘pass’;

END;

这段代码有什么问题,因为我在值@updatedStatus 中得到了意想不到的结果为null,它应该是'pass'

我在 stackoverflow 上关注 QA,但找不到解决方案。

我在 MacOS Catalina 中使用 MySQLWorkbench,MySQL 的版本是 8.0.19。

【问题讨论】:

    标签: mysql stored-procedures triggers procedure out-parameters


    【解决方案1】:

    过程中的OUT status参数与用户定义变量@status不同。这完全是两种不同的变量类型。

    所以,过程应该是这样的:

    create procedure Test_BEFORE_UPDATE_TEST (
    IN id int(5),
    OUT status enum('pass', 'fail')
    )
    begin
     set status = 'pass';
    END;
    

    在触发器中,你还应该使用DECLARE声明的普通变量:

    create trigger BEFORE_UPDATE_TEST 
    before update on test for each row 
    begin
    
    declare v_status enum('pass', 'fail');
    
    call Test_BEFORE_UPDATE_TEST(old.id, v_status);
    
    if (v_status is not null and v_status <> new.status) then
      set new.status = v_status;
    end if;
    
    end;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-26
      • 2020-05-12
      • 1970-01-01
      • 2012-11-29
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      相关资源
      最近更新 更多