I need to create a table based on the last id inserted into another main table, for this I created the following stored procedure:
CREATE PROCEDURE `sp_create_campaign`
(
IN p_vName VARCHAR(70),
IN p_iIdOper INT(11),
IN p_iIdCount INT(11),
IN p_iIdMoney INT(11),
IN p_cPrefix CHAR(2),
IN p_tComment TINYTEXT,
IN p_iIdUser VARCHAR(32),
OUT p_return_code TINYINT UNSIGNED
)
BEGIN
DECLARE p_campaign INT(11);
DECLARE exit handler for sqlexception
BEGIN
-- ERROR
set p_return_code = 1;
rollback;
END;
DECLARE exit handler for sqlwarning
BEGIN
-- WARNING
set p_return_code = 2;
rollback;
END;
START TRANSACTION;
-- Campaign
INSERT INTO `db_campaign`
(`vName`, `iIdOper`, `iIdCount`, `iIdMoney`, `cPrefix`, `tComment`, `iIdUser`, `dRegister`)
VALUES
(p_vName, p_iIdOper, p_iIdCount, p_iIdMoney, p_cPrefix, p_tComment, p_iIdUser, NOW());
SET p_campaign := LAST_INSERT_ID();
-- Sales
SET @s = CONCAT('DROP TABLE IF EXISTS ', 'db_sale_', p_campaign);
PREPARE stm FROM @s;
EXECUTE stm;
SET @x = CONCAT(
'CREATE TABLE ',
'db_sale_', p_campaign,
"(
`iIdSale` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`dDate` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
`dSubtotal` DECIMAL(7,2) UNSIGNED NOT NULL DEFAULT '00.00',
`dTax` DECIMAL(7,2) UNSIGNED NOT NULL DEFAULT '00.00',
`dTotal` DECIMAL(7,2) UNSIGNED NOT NULL DEFAULT '00.00',
`iIdMoney` INT(11) UNSIGNED NOT NULL,
`iIdOper` INT(11) UNSIGNED NOT NULL,
`iIdBankCount` INT(11) UNSIGNED NOT NULL,
`iIdGroup` INT(11) UNSIGNED NOT NULL,
`iIdUser` INT(11) UNSIGNED NOT NULL,
`iIdUserReg` VARCHAR(32) NOT NULL,
`dRegister` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`iIdSale`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;");
PREPARE stm FROM @x;
EXECUTE stm;
COMMIT;
-- SUCCESS
set p_return_code = 0;
END
But the problem is that only inserts the first record and fails to create the table. Where am I failing?
Replace this line: SET p_campaign := LAST_INSERT_ID();
With this one: SELECT LAST_INSERT_ID() INTO p_campaign ;
如果使用SET
,则需要=
而不是:=
Two things:
Executing DROP
will implicitly COMMIT
your transaction.
Try adding
DEALLOCATE PREPARE stm;
after each EXECUTE
statement.
According to MySQL documentation of last_insert_id()
If a stored procedure executes statements that change the value of LAST_INSERT_ID(), the changed value is seen by statements that follow the procedure call.
Use something like:
SELECT id INTO p_campaign FROM db_campaign ORDER BY id DESC LIMIT 1;
Or:
SELECT max(id) INTO p_campaign FROM db_campaign;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.