mysql存储过程检查记录是否存在

时间:2014-10-08 15:59:30

标签: mysql stored-procedures

我创建了以下存储过程:

CREATE DEFINER=`root`@`localhost` PROCEDURE `add_summit`(IN `assoc_code` CHAR(5), IN `assoc_name` CHAR(50), IN `reg_code` CHAR(2), IN `reg_name` CHAR(100), IN `code` CHAR(20), IN `name` CHAR(100), IN `sota_id` CHAR(5), IN `altitude_m` SMALLINT(5), IN `altitude_ft` SMALLINT(5), IN `longitude` DECIMAL(10,4), IN `latitude` DECIMAL(10,4), IN `points` TINYINT(3), IN `bonus_points` TINYINT(3), IN `valid_from` DATE, IN `valid_to` DATE)
BEGIN  
  declare assoc_id SMALLINT(5);
  declare region_id SMALLINT(5);
  declare summit_id MEDIUMINT(8);    

  -- ASSOCIATION check if an association with the given code and name already exists
  SELECT id INTO assoc_id FROM association WHERE code = assoc_code LIMIT 1;

  IF (assoc_id IS NULL) THEN
    INSERT INTO association(code, name) VALUES (assoc_code, assoc_name);
    set assoc_id = (select last_insert_id());
  END IF;

  -- REGION check if a region with the given code and name already exists
  SET region_id = (SELECT id FROM region WHERE code = reg_code AND name = reg_name AND association_id = assoc_id);
  IF (region_id IS NULL) THEN
    INSERT INTO region(association_id, code, name) VALUES (assoc_id, reg_code, reg_name);
    set region_id = (select last_insert_id());
  END IF;

  -- SUMMIT check if a summit with given parameters already exists
  SET summit_id = (SELECT id FROM summit WHERE association_id = assoc_id AND region_id = region_id);
  IF (summit_id IS NULL) THEN
    INSERT INTO summit(code, name, sota_id, association_id,  region_id, altitude_m, altitude_ft, longitude,
    latitude, points, bonus_points, valid_from, valid_to)
      VALUES (code, name, sota_id, assoc_id, region_id, altitude_m, altitude_ft, longitude, latitude,
      points, bonus_points, valid_from, valid_to);
  END IF;
END$$

基本上,它应检查某些表中是否存在记录,如果不存在,则应插入并使用插入的id(自动增量)。 问题是即使记录存在(例如在关联表中),assoc_id仍然返回null并导致记录重复。 我是存储过程的新手,所以我可能会做一些愚蠢的错误。我一直试图调试这个SP几个小时,但我找不到问题。

1 个答案:

答案 0 :(得分:0)

一个新手的错误。 我忘了在字段比较中指定表名,这导致与param名称(例如param名称)的一些冲突。 一个好主意是为参数指定某种前缀(如p_),并始终在SP中指定表的名称。