这里的目标是编写一个脚本尝试将新类别插入到类别表中,如果插入成功则消息:
1 row was inserted
如果更新不成功,该过程应显示此消息:
Row was not inserted - duplicate entry
每当我运行这个脚本时,无论运行多少次,我都会收到第二条消息,而实际上它应该显示第一条消息,然后是第二条消息。这是我的脚本。有人可以帮我发现我忽略了什么吗?谢谢。
use my_guitar_shop;
/*drop procedure if exists add_category;*/
DELIMITER //
CREATE PROCEDURE add_category(
in categories VARCHAR(100)
)
begin
declare duplicate_entry_for_key TinyINT DEFAULT FALSE;
declare continue handler for 1062
SET duplicate_entry_for_key = TRUE;
insert into categories values (5, 'Electric');
select '1 row was inserted.' as message;
if duplicate_entry_for_key = true then
select 'Row was not inserted - duplicate entry.' as message;
end if;
end //
DELIMITER ;
/* call the stored procedure with 'Gibson' */
call add_category('Gibson');
call add_category('Gibson');
最佳答案
您应该将 duplicate_entry_for_key
设置为 True。如果数据插入成功。
插入操作后做类似下面的事情。
SET duplicate_entry_for_key = last_insert_id();
或 请参阅下面的位检查示例。
例如:
START TRANSACTION; -- Begin a transaction
INSERT INTO categories
VALUES
(
5
,'Electric'
);
IF ROW_COUNT() > 0 THEN -- ROW_COUNT() returns the number of rows updated/inserted/deleted
SET duplicate_entry_for_key = TRUE;
COMMIT; -- Finalize the transaction
ELSE
SET duplicate_entry_for_key = False;
--You can ROLLBACK the transaction also - Revert all changes made before the transaction began
END IF
关于mysql - 如何在 MySQL 中编写一个在调用时显示两条消息的存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34196630/