简体   繁体   English

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

[英]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). 基本上,它应该检查记录是否存在于某些表中,如果不存在,则应将其插入并使用插入的ID(自动递增)。 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. 问题是,即使记录存在(例如,在关联表中),assoc_id仍返回null并导致记录重复。 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. 我一直在尝试调试此SP数小时,但找不到问题。

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. 一个好主意是为参数指定某种前缀(例如p_),并始终在SP中指定表的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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