如果不存在并插入mysql存储过程

时间:2014-09-01 02:03:11

标签: mysql stored-procedures insert-into

嘿伙计们,有人会在我的mysql代码中指出我的错误 我试图创建一个在触发器中调用的存储过程 是一个用户在books表中插入一本新书,如果callNumber不存在则bookqty表插入并在存在时更新,但在某些时候插入查询不起作用 但更新查询工作正常 提前谢谢你

use librarydb;
drop procedure if exists intoBooksQty;
delimiter $$

    create procedure intoBooksQty(in newcallNumber varchar(10))

        begin
            if not exists (select * from books where callNumber = newcallNumber) then
                insert into librarydb.bookqty(callNumber,bookQty,bookqtyOut) values (newcallNumber, 1,0);
            else
                update bookqty set bookQty = bookQty + 1 where callNumber = newCallNumber;
            end if;
        end$$

delimiter ;

1 个答案:

答案 0 :(得分:1)

一种选择是制作UPSERT。

DELIMITER //

CREATE PROCEDURE `intoBooksQty`(`newcallNumber` VARCHAR(10))
BEGIN
  INSERT INTO `bookqty` (`callNumber`, `bookQty`, `bookqtyOut`)
  SELECT `newcallNumber`, 1, 0
  FROM `books`
  WHERE `callNumber` = `newcallNumber`
    ON DUPLICATE KEY UPDATE `bookQty` = `bookQty` + 1;
END//

DELIMITER ;

SQL Fiddle demo