为什么 Mysql 在存储过程中总是 returns 零值?

Why Mysql always returns zero value withing stored procedure?

如果 table;

中不存在,我使用以下来保留 id
CREATE DEFINER=`root`@`localhost` PROCEDURE `get_ch_id_from_ych_id`(pYch_id nvarchar(100), pIP_address nvarchar(30))
BEGIN
declare ch_id bigint;
set ch_id =(select ifnull(max(ch_id),0)ch_id from channels where ych_id=pYch_id);
if(ch_id<1) then 
    INSERT INTO channels
    (ych_id, Name, Last_IP, Active, Banned, Qualified, ReportedCount)
    VALUES
    (pYch_id,Name,pIP_address,1      ,0     ,0        ,0);
end if;
select ifnull(max(ch_id),0) ch_id from channels where ych_id=pYch_id;
END

然而,当如下调用时它总是return零;

call get_ch_id_from_ych_id ('A',''); //not work
select ifnull(max(ch_id),0) ch_id from channels where ych_id='A'; //works    

数据行插入没有问题并且存在于table中。但在第一行, 它 return 为零。当我 运行 sql 在 workbench 它 return 的正确值。这里有什么问题?

我不认为你可以在 MySQL 中做到这一点。 您需要将存储过程转换为函数或将 OUT 参数用于 return 值。

来源:MySQL - Returning Single Value from Stored Procedure

不要为您提供与 table 列同名的局部变量。当您在查询中引用 ch_id 时,它使用变量而不是列。

CREATE DEFINER=`root`@`localhost` PROCEDURE `get_ch_id_from_ych_id`(pYch_id nvarchar(100), pIP_address nvarchar(30))
BEGIN
declare temp_ch_id bigint;
set temp_ch_id =(select ifnull(max(ch_id),0)ch_id from channels where ych_id=pYch_id);
if(temp_ch_id<1) then 
    INSERT INTO channels
    (ych_id, Name, Last_IP, Active, Banned, Qualified, ReportedCount)
    VALUES
    (pYch_id,Name,pIP_address,1      ,0     ,0        ,0);
end if;
select ifnull(max(ch_id),0) ch_id from channels where ych_id=pYch_id;
END