MySQL 存储过程传参的一个坑

╰+哭是因爲堅強的太久メ 2021-12-21 13:17 271阅读 0赞

例如一个存储过程:

  1. delimiter //
  2. create procedure read_score(IN id int)
  3. begin
  4. select * from score where id=id;
  5. end;
  6. //
  7. delimiter ;

在这种情况下,无论我传入id是什么值,这个存储过程都会返回score的所有数据。
原因是当传入参数的名字跟字段名字相等的时候,那么参数名字就不会替换成实际参数,上述例子的SQL也就是始终是执行SQLselect * from score where id=id;,因为id=id恒为真,所以实际等效于select * from score

对于查询还好,万一SQL是delete from score where id=id呢?所以需要特别注意,解决方法就是形式参数要跟表字段区分开来,例如

  1. create procedure read_score(IN prd_id int)
  2. begin
  3. select * from score where id=prd_id;
  4. end;
  5. //

发表评论

表情:
评论列表 (有 0 条评论,271人围观)

还没有评论,来说两句吧...

相关阅读