简体   繁体   中英

mysql stored procedure checking if record exists

I created the following stored procedure:

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$$

basically, it should check if a record exists in some tables and, if it doesn't, it should insert it and use the inserted id (auto increment). The problem is that even if the record exists (for instance in the association table), assoc_id keeps returning null and that leads to record duplication. I'm new to stored procedures so I may be doing some stupid errors. I've been trying to debug this SP for hours but I cannot find the problem.

A newbie mistake. I forgot to specify the table name in the field comparison and that leads to some conflicts with param names (for example the param name). A good idea is to specify some kind of prefix for parameters (like p_) and always specify the name of the table in the SP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM