将值传递给另一个插入查询MySQL

时间:2015-04-03 10:34:52

标签: 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 ;

上面的查询将检查插入的作者是否存在于作者表中,否则如果存在则不会插入... 我的问题:

  1. 我希望获得fname和surname,如果存在变量那么 插入另一个插入另一个表的查询需要 2变量如何将其传递给查询?
  2. 如果存在,我将使用authorid然后选择fname和surname 属于authorid?
  3. 我可以声明参数而不是实际值' xxxx'?
  4. 谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

你关闭,试试这个:

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 ;