【问题标题】:Mysql Stored procedure issue with varchar variable in where clauseMysql存储过程问题与where子句中的varchar变量
【发布时间】:2014-05-12 08:13:44
【问题描述】:

我在 mysql 存储过程中遇到问题,其中 where 子句中的 varchar 变量不返回结果。查询如下。

declare itcode varchar(30);
declare qty int;
declare finished int;
declare testc cursor for 
    select itemcode from mytable limit 0,10;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
open testc;
read_loop:Loop
    fetch testc into itcode;
    if finished=1 then
        leave read_loop;
    end if;
    select sum(Qty) as total from 
            mytable2 
            where itemcode=itcode;
end loop;
close testc;

在上面的语句中,即使项目代码在两个表上都存在,它也会返回null。但是,如果我在 where close 上使用手动分配的值编写语句,如下所示。

select sum(Qty) as total from mytable2 where itemcode='p2343';

我无法弄清楚为什么 varchar 变量在 where 子句中不起作用。有人可以帮我弄清楚如何解决这种类型的问题吗?

注意:两个表列都是 varchar(30)。

附加说明:当我如下更改语句时,它也会打印 itcode 中的值。

select sum(Qty) as total,itcode from mytable2 where itemcode=itcode

所以 itcode 的值为 'p2343' 但上面的存储过程不起作用。

【问题讨论】:

  • where itemcode like 'p2343'; 有效吗?
  • 是的,当我用单引号作为字符串给出时,它可以工作。但是当我分配变量时它不起作用。
  • 那么where itemcode like itcode; 呢?
  • 也试过了,还是不行。
  • 您的 itcode 似乎没有值 'p2343'。

标签: mysql sql stored-procedures where-clause varchar


【解决方案1】:

这里的问题是该过程引用了您的全局变量qty,而不是mytable2 上的Qty 列。尝试改变这个:

declare qty int;

到这里

declare v_qty int;

【讨论】:

  • 非常感谢。我到处搜索以解决这个问题。只是为了理解,mysql不会识别字段和变量的大小写差异吗?
  • 通常取决于操作系统。 Unix=是,Windows 和 Mac OS=否。查看更多信息:dev.mysql.com/doc/refman/5.7/en/…
猜你喜欢
  • 1970-01-01
  • 2011-02-08
  • 1970-01-01
  • 1970-01-01
  • 2013-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多