简体   繁体   English

将值(如果存在)传递给另一个插入查询MySQL

[英]passing the value if exists to another insert query MySQL

I have the following query running against mysql: 我对mysql运行以下查询:

DELIMITER $$

CREATE
    /*[DEFINER = { user | CURRENT_USER }]*/
    PROCEDURE `mybook_store`.`myProc`()
    /*LANGUAGE SQL
    | [NOT] DETERMINISTIC
    | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
    | SQL SECURITY { DEFINER | INVOKER }
    | COMMENT 'string'*/
   BEGIN
    DECLARE authId INT DEFAULT 0;
    DECLARE 
    DECLARE CheckExists INT DEFAULT 0;  
    SET CheckExists = 0;
    SELECT COUNT(*) INTO CheckExists FROM author WHERE fname = 'xxxx' AND surname='xxxx'; 
        IF (CheckExists > 0) THEN
        SELECT  authorid INTO authId FROM author WHERE fname = 'xxxx' AND surname='xxxx';
            ELSE 

            INSERT author(fname, surname) VALUES('xxxx', 'xxxx');
            SET authId = LAST_INSERT_ID();

        END IF;


    END$$

DELIMITER ;

the above query will check if the inserted author exists in author table if not it will insert it if exist will not insert... my questions: 上面的查询将检查插入的作者是否在作者表中,如果不存在,它将插入它,如果存在,则不会插入...我的问题:

  1. i want to to get fname and surname if exists to variables then insert in another query which insert into another table requires the 2 variables how to pass it to the query? 我想获取fname和surname(如果变量存在),然后插入另一个查询,该查询插入另一个表需要2个变量如何将其传递给查询?
  2. shall i use the authorid if exists then select fname and surname that belong to authorid? 如果存在我应该使用authorid,然后选择属于authorid的fname和firstname?
  3. can i declare parameters instead of the actual value 'xxxx'? 我可以声明参数而不是实际值“ xxxx”吗?

thank you for your help 谢谢您的帮助

You're close, try this: 您接近了,试试这个:

DELIMITER $$
CREATE PROCEDURE myProc (IN f_fname VARCHAR(25), IN f_surname VARCHAR(25))
BEGIN
  DECLARE checkExists INT DEFAULT 0;
  DECLARE authId INT DEFAULT 0;
  SELECT COUNT(*) INTO checkExists FROM author WHERE fname = f_fname AND surname = f_surname;
  IF(checkExists > 0) THEN
    SELECT authorId into authId FROm author WHERE fname = f_fname AND surname = f_surname;
  ELSE
    INSERT INTO author(fname, surname) VALUES (f_fname, f_surname);
    SET authId = LAST_INSERT_ID();
  END IF;
END$$
DELIMITER ;

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

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